zoukankan      html  css  js  c++  java
  • 使用 JavaScript开发的跨平台音乐、书籍播放器

    代码地址如下:
    http://www.demodashi.com/demo/12542.html

    演示效果

    歌曲推荐界面

    歌手搜索界面

    歌词预览界面

    书籍推荐界面

    代码实现过程

    首页代码:

    'use strict';
    import React, { Component } from 'react';
    import ReactDOM from 'react-dom';
    import './style.css';
    import $ from 'jquery';
    import Message from 'lrh-message';
    
    export default class Dashboard extends Component {
        constructor() {
            super();
            this.current = 1;
            this.state = {
                folderList: []
            }
        }
    
        componentDidMount() {
            $.subscribe('closeDashboard', () => {
                $('.dashboard').hide();
            });
    
            $.subscribe('showDashboard', () => {
                $('.dashboard').show();
            });
    
            $('.defaultSelected').click();
        }
    
        loadTuiJianFolder(page) {
            if (typeof page !== 'number') {
                this.addSelectedClass(page);
                page = 1;
            }
            this.current = page;
            let url = 'http://www.kugou.com/yy/special/index/' + page + '-0-1.html';
            $.get(url, (result) => {
                let $li = $(result).find('#ulAlbums li');
                let list = [];
                $.each($li, (i, item) => {
                    let folder = {
                        title: $(item).find('a').attr('title'),
                        url: $(item).find('a').attr('href'),
                        image: $(item).find('img').attr('_src')
                    }
                    list.push(folder);
                });
                if (list.length > 10) {
                    list.length = 10;
                }
                this.setState({ folderList: list });
            }).fail(function () {
                new Message('warning', '载入歌曲分类失败。');
            });
        }
    
        goToThisMusicList(e) {
            let page = $(e.target).text();
            this.loadTuiJianFolder(Number(page));
        }
    
        loadMusicList(e) {
            let url = $(e.target).parent().attr('data');
            if (url.indexOf('singer') !== -1) {
                let value = $(e.target).next().text();
                let url = `http://mobilecdn.kugou.com/api/v3/search/song?format=jsonp&keyword=${value}&page=1&pagesize=30&showtype=1&callback=kgJSONP238513750<span style="white-space:pre"></span>`;
                $.ajax({
                    url: url,
                    method: 'GET',
                    contentType: 'json',
                    success: (result) => {
                        result = result.substring(1, result.length - 1);
                        $.publish('showMusicByThisList', { result: result });
                        $.publish('listBySearch');
                        $.publish('closeDashboard');
                        $.publish('closeArticleDashboard');
                    },
                    error: (error) => {
                        new Message('warning', '搜索歌曲失败,请重新搜索。');
                    }
                })
            } else {
                $.get(url, (result) => {
                    let $li = $(result).find('#songs li');
                    let songs = {
                        data: {
                            info: []
                        }
                    };
                    $.each($li, (i, item) => {
                        let music = {
                            songname: $(item).find('.text').text().split(' - ')[1],
                            singername: $(item).find('.text').text().split(' - ')[0],
                            hash: $(item).find('a').attr('data').split('|')[0],
                            album_name: '',
                            duration: ''
                        };
                        songs.data.info.push(music);
                    });
                    $.publish('showMusicByThisList', { result: JSON.stringify(songs) });
                    $.publish('closeDashboard');
                    $.publish('listBySearch');
                }).fail(function () {
                    new Message('warning', '歌曲加载失败,请重新点击。');
                });
            }
        }
    
        loadSinger(e) {
            this.addSelectedClass(e);
            let url = 'http://www.kugou.com/yy/html/singer.html';
            $.get(url, (result) => {
                let $li = $(result).find('#list_head li');
                let list = [];
                $.each($li, (i, item) => {
                    let folder = {
                        title: $(item).find('a').attr('title'),
                        url: 'singer' + i,
                        image: $(item).find('img').attr('_src')
                    }
                    list.push(folder);
                });
                this.setState({ folderList: list });
            }).fail(function () {
                new Message('warning', '加载热门歌手失败,请尝试重新点击。');
            });
        }
    
        addSelectedClass(e) {
            $('.musicNavbar li').removeClass('selectedNavbar');
            $(e.target).addClass('selectedNavbar');
        }
    
        render() {
            let current = this.current;
            let page = [];
            if (this.state.folderList[0] && this.state.folderList[0].url.indexOf('singer') === -1) {
                for (let i = 0; i < 5; i++) {
                    if (i + 1 === current) {
                        page.push(<li key={Math.random()} className="musicCurrentPage">{i + 1}</li>);
                    } else {
                        page.push(<li key={Math.random()} onClick={this.goToThisMusicList.bind(this)}>{i + 1}</li>);
                    }
                }
            }
    
            let folderList = this.state.folderList.map((folder, i) => {
                return (
                    <li className="oneFolder" key={i} data={folder.url}>
                        <img style={{'150px',height:'150px'}} src={folder.image} onClick={this.loadMusicList.bind(this)} />
                        <p className="folderTitle" title={folder.title}>{folder.title}</p>
                    </li>
                )
            });
            return (
                <div className="dashboard">
                    <ul className="musicNavbar">
                        <li className="selectedNavbar defaultSelected" onClick={this.loadTuiJianFolder.bind(this)}>个性推荐</li>
                        <li onClick={this.loadSinger.bind(this)}>热门歌手</li>
                    </ul>
                    <ul>{folderList}</ul>
                    <ul className="musicPagination">
                        {page}
                    </ul>
                </div>
            )
        }
    }
    

    歌词预览代码:

    'use strict';
    import React, { Component } from 'react';
    import ReactDOM from 'react-dom';
    import './style.css';
    import $ from 'jquery';
    import Message from 'lrh-message';
    
    export default class MusicDetail extends Component {
        constructor() {
            super();
            this.state = {
                image: './static/images/panda.jpg',
                songName: '未知',
                singername: '未知',
                lyric: '没有歌词',
                audioName: '未知'
            }
        }
    
        componentDidMount() {
            $.subscribe('openBigWindow', () => {
                $('.musicDetail').show();
            });
    
            $.subscribe('selectedOneMusic', (o, args) => {
                this.setDetail(args.hash);
            });
    
            $.subscribe('changeLyricLine', (o, args) => {
                this.changeLyricLine(args);
            });
        }
    
        changeLyricLine(args) {
            let $lyricLineGroup = $('.lyricLine');
            $.each($lyricLineGroup, (i, item) => {
                let timeStr = $(item).attr('id').substring(1, 6);
                let time = Number(timeStr.split(':')[0]) * 60 + Number(timeStr.split(':')[1]);
                if (time === args.time) {
                    $(item).get(0).scrollIntoView(true);
                    let top = $('.detailLyric').get(0).scrollTop;
                    $('.detailLyric').get(0).scrollTop = top - 100;
                    $('.lyricLine').css({
                        color: '#000'
                    });
                    $(item).css({
                        color: '#fff'
                    });
                }
            });
        }
    
        setDetail(hash) {
            if(hash.indexOf('local') !== -1){
                this.setState({ image: './static/images/panda.jpg' });
                this.setState({ songName: $('#' + hash).attr('data').split(' - ')[0].split('/')[1] });
                this.setState({ singername: $('#' + hash).attr('data').split(' - ')[1].split('.mp3')[0] });
                this.setState({ lyric: '没有歌词' });
                this.setState({ audioName: '未知' });
                return;
            }else if(hash.indexOf('article') !== -1){
                this.setState({ image: './static/images/panda.jpg' });
                this.setState({ songName: '未知'});
                this.setState({ singername: '未知' });
                this.setState({ lyric: '没有歌词' });
                this.setState({ audioName: '未知' });
                return;
            }
            let url = `http://www.kugou.com/yy/index.php?r=play/getdata&hash=${hash}`;
            $.ajax({
                url: url,
                method: 'GET',
                contentType: 'json',
                success: (result) => {
                    this.setState({ image: JSON.parse(result).data.img });
                    this.setState({ songName: JSON.parse(result).data.song_name });
                    this.setState({ singername: JSON.parse(result).data.author_name });
                    this.setState({ audioName: JSON.parse(result).data.audio_name });
                    let lyrics = JSON.parse(result).data.lyrics;
                    for(let i = 0; i < 13; i++){
                        lyrics += '[lyric'+ i +'] 
    ';
                    }
                    this.setState({ lyric: lyrics });
                },
                error: (error) => {
                    new Message('warning', '获取歌曲信息失败。');
                }
            })
        }
    
        closeBigWindow() {
            $('.musicDetail').hide();
        }
    
        render() {
            this.lyrics = this.state.lyric.split('
    ');
            let lyricLine = this.lyrics.map((line) => {
                return (
                    <p title={line.split(']')[1]} className="lyricLine" key={Math.random()} id={line.split(']')[0]}>{line.split(']')[1]}</p>
                )
            });
            return (
                <div className="musicDetail">
                    <div className="detailHeader"><i className="fa fa-compress" aria-hidden="true" onClick={this.closeBigWindow.bind(this)}></i></div>
                    <div className="detailContent">
                        <img className="musicImg" src={this.state.image} />
                        <img className="musicBar" src="./static/images/bar.png" />
                        <p className="detailName">
                            <span title={this.state.songName} style={{ fontWeight: 'bold', fontSize: '20px', display: 'inline-block', marginBottom: '10px',overflow:'hidden', '300px' }}>{this.state.songName}</span><br />
                            <span style={{fontWeight: 'bold',display: 'inline-block', marginRight: '10px',  '100px'}}>歌手: {this.state.singername}</span>
                            <span style={{fontWeight: 'bold', display: 'inline-block',  '190px'}}>专辑: {this.state.audioName.substring(0, 10)}</span>
                        </p>
                        <div className="detailLyric">{lyricLine}</div>
                    </div>
                </div>
            )
        }
    }
    

    项目文件结构截图

    注:

    下载之后请先将后缀名 .zip 改成 .7z再进行解压使用 JavaScript开发的跨平台音乐、书籍播放器

    代码地址如下:
    http://www.demodashi.com/demo/12542.html

    注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

  • 相关阅读:
    重视个人成长 远离心灵鸡汤——由一则“心灵鸡汤”想到的
    vim 学习
    针对不同包之间的action跳转,怎么配置?
    Bootstrap 栅格系统
    struts2的s:iterator 标签 详解
    struts2 <s:property/>标签的使用--输出时间格式转换
    Myeclipse中把java代码导成UML类图
    大学毕业后坚持学习有什么用
    【BZOJ2754】喵星球上的点名(AC自动机)
    Codeforces Round #466 (Div. 2)
  • 原文地址:https://www.cnblogs.com/demodashi/p/8512862.html
Copyright © 2011-2022 走看看