LRolinx

前言

前面我们获取了歌曲的排行榜的数据,我们现在需要实现歌曲播放

前面我们写了一段函数来得到了回调的数据,现在我们需要使用这一段数据,来实现播放歌曲

完整代码

<!DOCTYPE html>
<html lang="zh-cn" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>QQ音乐API</title>
    <link rel="icon" href="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1554453627219&di=fd6b1db82c1878273c5e889c5300c390&imgtype=0&src=http%3A%2F%2Fpic.90sjimg.com%2Fdesign%2F01%2F23%2F72%2F30%2F58fdf1c8cf2d3.png">
    <link href="~/Content/Css/style.css" rel="stylesheet" />
    
</head>
<body>

    <div id="bg2"></div>
    <div id="bg"></div>

    <div style="position: fixed; top: 0%; left: 50%; transform: translate(-50%); width: 100%;">
        <h1>当前播放-</h1>
        <div id="info"></div>
        <div class="Centent_D">
            <input id="SongText" type="text" placeholder="搜索歌曲" />
            <input type="button" value="搜索并播放" onclick="SerchSongOrPlay()" />
            <div style="max-height: 500px; overflow-y: auto">
                <table cellspacing="0" id="table">
                    <thead>
                        <tr>
                            <td>歌名</td>
                            <td>歌手</td>
                            <td hidden>索引</td>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <canvas id=\'canvas\' width="600" height="350"></canvas>
            <audio src="" crossOrigin="anonymous" id="audio" loop controls></audio>
        </div>
    </div>

<div id="audio_control">
    <p id="SongTime"><span class="SongTime"></span><span class="PlaySongTime"></span></p>
    <input type="button" value="BackSong" onclick="BackSong()" />
    <input type="button" value="NextSong" onclick="NextSong()" />
    <input type="button" value="切换播放模式" onclick="PlayMode(3)" />
    <input id="SongSpeed" type="range" min="1" max="4" value="1" />
    <p>遇到播放不了?可能你用的是谷歌浏览器,解决方法:地址栏输入:chrome://flags/#autoplay-policy回车,在Autoplay policy高亮这一行右边的按钮选择No user gesture is required,重启浏览器即可</p>
    <div id="SongLyric">
        <div id="qrc_ctn" class="qrc_ctn">

        </div>
    </div>
    <p id="SongProgress"></p>
</div>
    <script src="~/Content/Javascript/jquery.min.js"></script>
    <script src="~/Content/Javascript/main.js"></script>
    <script src="~/Content/Javascript/Vibrant.min.js"></script>
    <script src="~/Content/Javascript/TimeToPack.js"></script>
<script>

    function SetTimeRutrunMS(AudioTime) {
        var M, S, MS;
        M = parseInt(AudioTime / 60);
        S = (AudioTime % 60).toFixed(2);
        M += \'\';
        S += \'\';
        M = (M.length == 1) ? \'0\' + M : M;
        S = (S.length == 4) ? \'0\' + S : S;
        return [M, S];
    }

    function SetMSRutrunms(MS) {
        if (MS != undefined) {
            if (MS.search(/\d\d\D\d\d\D\d\d/) === 0) {
                var AF = MS.match(/(.*)\:/);
                var AM = MS.match(/\:(.*)\./);
                var AHM = MS.match(/\.(.*)/);
                var HBJS = AF[1] + "." + AM[1] + AHM[1];

                return HBJS;


            } else {
                return "格式不对";
            }
        } else {
            return false;
        }
    }

    function SetMHMRutrunms(MH) {
        if (MH != undefined || MH != 0 || MH != null) {

            var AA;
            var CC = MH % 60 /100;
            if (MH / 60 <= 1) {
                AA = MH / 100;
            } else {
                AA = parseInt(MH / 60) + CC;
            }
            return AA;
        } else {
            return false;
        }
    }

    function VerifySongTime(num) {
        if (num != undefined || num != "" || num != null) {
            if (num.search(/\d\d\D\d\d\D\d\d/) == 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    function AJBXC(ValueA,ValueB,Max) {
        var XJJG = ValueA - ValueB;
        if (XJJG < 0) {
            XJJG -= XJJG * 2
        }
        if (XJJG <= Max){
            return true;
        }
        return false;
    }
</script>
    <script>
        var audio = $("#audio");
        var songAttr = [];
        var SonglrcAttr = [];
        var songindex = 0;
        var lycinner = 0;
        var ToleranceInt = 1;
        var time1, time2, time3;
        var BackWeek = _.GetDayToWeek(_.GetOneYearToDay());

        function MusicJsonCallbacktoplist(data) {
            var TemporarySingerApp = "";
            if (window.navigator.onLine) {
                songAttr = data;
                if (songAttr.songlist.length != 0) {
                    $("table tbody").empty();
                    $.each(songAttr.songlist,
                        function (e) {
                            TemporarySingerApp += "<tr><td>" + this.data.songname + "</td><td>";
                            $.each(songAttr.songlist[e].data.singer,
                                function (i) {
                                    TemporarySingerApp += " " + songAttr.songlist[e].data.singer[i].name + " ";
                                    if (i == (songAttr.songlist[e].data.singer.length - 1)) {
                                        TemporarySingerApp += "</td><td hidden>" + e + "</td></tr>";
                                        $("table tbody").append(TemporarySingerApp);
                                        TemporarySingerApp = "";
                                    }

                                });
                        });
                    $("table tbody tr").on("dblclick",
                        function () {
                            if (!$(this).attr("disabled")) {
                                songindex = parseInt($(this).find("td").last()[0].innerHTML);
                                RecommendSongIPVkey(parseInt($(this).find("td").last()[0].innerHTML), 1);
                                RemoveLyricinfo();
                            }
                        });
                    RecommendSongIPVkey(0, 1);
                } else {
                    console.log("找不到音乐");
                }
            } else {
                console.log("你没有网络,请求了数据无法返回");
            }
        }

        function RecommendSongIPVkey(i, z) {
            $("table tbody tr").css("background", "");
            $("table tbody tr:nth-of-type(" + (i + 1) + ")").css("background", "rgba(204, 204, 204,0.3)");
            if (songAttr.songlist[i].songid != 0) {
                $.ajax({
                    type: "GET",
                    dataType: "jsonp",
                    url:
                        \'https://u.y.qq.com/cgi-bin/musicu.fcg?data={"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"000000000","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"000000000","songmid":["\' +
                            songAttr.songlist[i].data.songmid +
                            \'"],"songtype":[0],"uin":"0","loginflag":1,"platform":"20"}}}\',
                    success: function (Vkeydata) {
                        if (window.navigator.onLine) {
                            songindex = i;
                            if (Vkeydata.req_0.data.midurlinfo[0].vkey != "") {
                                GetSong(Vkeydata);

                                $.ajax({
                                    type: "GET",
                                    dataType: "json",
                                    url: "/Index/GetMuiscLyric",
                                    data: {
                                        Url:"https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?-=MusicJsonCallback_lrc&pcachetime=" +Math.round(new Date()) +"&songmid=" +songAttr.songlist[i].data.songmid +"&g_tk=5381&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0",
                                        Filename: songAttr.songlist[i].data.albummid + ".json"
                                    },
                                    success: function (data) {
                                        var SongData = JSON.parse(data);
                                        var SongLyric = decodeURIComponent(escape(window.atob(SongData.lyric)));
                                        var SongLyricDOM = $("#SongLyric > div");
                                        SongLyricDOM.children("p").remove();
                                        SongLyric.trim().split(\'\n\').forEach(function (v, i) {

                                            var LryTime = v.match(/\[(.*)\]/)[1];
                                            var Lry = v.match(/\](.*)/)[1];
                                            if (VerifySongTime(LryTime)) {
                                                SonglrcAttr.push([SetMSRutrunms(LryTime), Lry]);

                                                SongLyricDOM.append("<p data-id=" + i + ">" + Lry + "</p>");
                                            } else {
                                                SonglrcAttr.push([Lry, LryTime]);
                                                SongLyricDOM.append("<p data-id=" + i + ">" + LryTime + "</p>");
                                            }

                                        });
                                    }
                                });

                                if (songAttr.songlist[i].data.albummid != "") {

                                    $("#bg").css("background-image",
                                        "url(\'https://y.gtimg.cn/music/photo_new/T002R300x300M000" +
                                        songAttr.songlist[i].data.albummid +
                                        ".jpg?max_age=2592000\')");
                                    $.ajax({
                                        type: "GET",
                                        dataType: "json",
                                        url: "/Index/GetMusicPic",
                                        data: {
                                            Url: "https://y.gtimg.cn/music/photo_new/T002R300x300M000" +
                                                songAttr.songlist[i].data.albummid +
                                                ".jpg?max_age=2592000",
                                            Filename: songAttr.songlist[i].data.albummid + ".jpg"
                                        },
                                        success: function (filename) {
                                            if (filename != null) {
                                                var img = document.createElement(\'img\');
                                                img.setAttribute(\'src\', \'../Content/MusicPic/\' + filename);

                                                img.addEventListener(\'load\',
                                                    function () {
                                                        var vibrant = new Vibrant(img);
                                                        var swatches = vibrant.swatches();
                                                        if (swatches.Vibrant != undefined) {
                                                            $("body").css("background-color",
                                                                "rgba(" +
                                                                swatches.Vibrant.rgb[0] +
                                                                "," +
                                                                swatches.Vibrant.rgb[1] +
                                                                "," +
                                                                swatches.Vibrant.rgb[2] +
                                                                ",1)");
                                                        }
                                                    });
                                            }
                                        }
                                    });
                                } else {
                                    $("#bg").css("background-image", "url(\'../Content/MusicPic/NoMusicPic.jpg");
                                }

                                $("h1").html("当前播放 - " + songAttr.songlist[i].data.songname);
                            } else {
                                NoCopyright(i, z);
                            }
                        } else {
                            console.log("你没有网络,接收不到返回的数据");
                        }
                    },
                    error: function (e) {
                        if (e.state == "404") {
                            RecommendSongIPVkey(i, z);
                        }
                    }
                });
            } else {
                NoCopyright(i, z);
            }
        }
        $.ajax({
            type: "GET",
            dataType: "jsonp",
            url: \'https://c.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg?topid=26&platform=yqq.json&jsonpCallback=MusicJsonCallbacktoplist\'
        });

        function callback(data) {
            if (window.navigator.onLine) {
                songAttr = data;
                if (songAttr.data.song.list.length != 0) {
                    $("table tbody").empty();
                    $.each(songAttr.data.song.list,
                        function (e) {
                            $("table tbody").append("<tr><td>" +
                                this.songname +
                                "</td><td>" +
                                this.singer[0].name +
                                "</td><td hidden>" +
                                e +
                                "</td></tr>");
                        });
                    $("table tbody tr").on("dblclick",
                        function () {
                            if (!$(this).attr("disabled")) {
                                songindex = parseInt($(this).find("td").last()[0].innerHTML);
                                SongIPVkey(parseInt($(this).find("td").last()[0].innerHTML), 1);
                                RemoveLyricinfo();
                            }
                        });
                    SongIPVkey(0, 1);
                } else {
                    console.log("找不到音乐");
                }
            } else {
                console.log("你没有网络,请求了数据无法返回");
            }
        }

        function SongIPVkey(i, z) {
            $("table tbody tr").css("background", "");
            $("table tbody tr:nth-of-type(" + (i + 1) + ")").css("background", "rgba(204, 204, 204,0.3)");
            if (songAttr.data.song.list[i].songid != 0) {
                $.ajax({
                    type: "GET",
                    dataType: "jsonp",
                    url:
                        \'https://u.y.qq.com/cgi-bin/musicu.fcg?data={"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"000000000","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"000000000","songmid":["\' +
                            songAttr.data.song.list[i].songmid +
                            \'"],"songtype":[0],"uin":"0","loginflag":1,"platform":"20"}}}\',
                    success: function (Vkeydata) {
                        if (window.navigator.onLine) {
                            songindex = i;
                            if (Vkeydata.req_0.data.midurlinfo[0].vkey != "") {
                                GetSong(Vkeydata);
                                GetSongLyric(i);
                                GetSongImg(i);
                                $("h1").html("当前播放 - " + songAttr.data.song.list[i].songname);
                            } else {
                                NoCopyright(i, z);
                            }
                        } else {
                            console.log("你没有网络,接收不到返回的数据");
                        }
                    },
                    error: function (e) {
                        if (e.state == "404") {
                            SongIPVkey(i, z);
                        }
                    }
                });
            } else {
                NoCopyright(i, z);
            }
        }

        function GetSong(Songdata) {
            audio[0].src = Songdata.req.data.freeflowsip[0] + Songdata.req_0.data.midurlinfo[0].purl;
            audio.html("<source src=" + Songdata.req.data.freeflowsip[0] + Songdata.req_0.data.midurlinfo[0].purl + " />");
            console.log(audio[0].networkState);
            if (audio[0].networkState === 3) {
                audio[0].muted = false;
                    audio[0].play();
                PlayMode(3);

            }
        }


        function GetSongLyric(i) {
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "/Index/GetMuiscLyric",
                data: {
                    Url: "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?-=MusicJsonCallback_lrc&pcachetime=" +
                        Math.round(new Date()) +
                        "&songmid=" +
                        songAttr.data.song.list[i].songmid +
                        "&g_tk=5381&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0",
                    Filename: songAttr.data.song.list[i].albummid + ".json"
                },
                success: function (data) {

                    var SongData = JSON.parse(data);
                    var SongLyric = decodeURIComponent(escape(window.atob(SongData.lyric)));
                    var SongLyricDOM = $("#SongLyric > div");
                    SongLyricDOM.children("p").remove();
                    SongLyric.trim().split(\'\n\').forEach(function (v, i) {

                        var LryTime = v.match(/\[(.*)\]/)[1];
                        var Lry = v.match(/\](.*)/)[1];
                        if (VerifySongTime(LryTime)) {
                            SonglrcAttr.push([SetMSRutrunms(LryTime), Lry]);

                            SongLyricDOM.append("<p data-id=" + i + ">" + Lry + "</p>");
                        } else {
                            SonglrcAttr.push([Lry, LryTime]);
                            SongLyricDOM.append("<p data-id=" + i + ">" + LryTime + "</p>");
                        }

                    });

                }
            });
        }

        function GetSongImg(i) {

            if (i != null) {
                if (songAttr.data.song.list[i].albummid !== "") {

                    $("#bg").css("background-image",
                        "url(\'https://y.gtimg.cn/music/photo_new/T002R300x300M000" +
                        songAttr.data.song.list[i].albummid +
                        ".jpg?max_age=2592000\')");
                    $.ajax({
                        type: "GET",
                        dataType: "json",
                        url: "/Index/GetMusicPic",
                        data: {
                            Url: "https://y.gtimg.cn/music/photo_new/T002R300x300M000" +
                                songAttr.data.song.list[i].albummid +
                                ".jpg?max_age=2592000",
                            Filename: songAttr.data.song.list[i].albummid + ".jpg"
                        },
                        success: function (filename) {
                            if (filename != null) {
                                var img = document.createElement(\'img\');
                                img.setAttribute(\'src\', \'../Content/MusicPic/\' + filename);

                                img.addEventListener(\'load\',
                                    function () {
                                        var vibrant = new Vibrant(img);
                                        var swatches = vibrant.swatches();
                                        if (swatches.Vibrant !== undefined) {
                                            $("body").css("background-color",
                                                "rgba(" +
                                                swatches.Vibrant.rgb[0] +
                                                "," +
                                                swatches.Vibrant.rgb[1] +
                                                "," +
                                                swatches.Vibrant.rgb[2] +
                                                ",1)");
                                        }
                                    });
                            }
                        }
                    });
                } else {
                    $("#bg").css("background-image", "url(\'../Content/MusicPic/NoMusicPic.jpg");
                }
            }
        }

        function SerchSongOrPlay() {
            var SongText = $("#SongText");
            if (window.navigator.onLine) {
                if (SongText.val().trim() !== "") {
                    $.ajax({
                        type: "GET",
                        dataType: \'jsonp\',
                        url: "https://c.y.qq.com/soso/fcgi-bin/client_search_cp?aggr=1&cr=1&flag_qc=0&p=1&n=10&w=" +
                            SongText.val().trim() +
                            ""
                    });
                    SongText.val("");
                } else {
                    alert("请输入要搜索的歌曲");
                    return;
                }
            } else {
                alert("你没有网络,数据没发送出去");
            }

        }

        function NoCopyright(i, z) {
            if (z === 1) {
                $("h1").html("你搜索的歌没有播放版权!已帮你自动切换下一首");
                $("table tbody tr:nth-of-type(" + (i + 1) + ")").css("color", "#aaa");
                $("table tbody tr:nth-of-type(" + (i + 1) + ")").attr("disabled", true);
                NextSong();
            } else {
                $("h1").html("你搜索的歌没有播放版权!已帮你自动切换上一首");
                $("table tbody tr:nth-of-type(" + (i + 1) + ")").css("color", "#aaa");
                $("table tbody tr:nth-of-type(" + (i + 1) + ")").attr("disabled", true);
                BackSong();
            }

        }

        function BackSong() {
            RemoveLyricinfo();
            if (songAttr.data != undefined) {
                if (songindex > 0) {
                    songindex -= 1;
                    SongIPVkey(songindex, 0);
                } else {
                    songindex = songAttr.data.song.list.length;
                    SongIPVkey((songindex - 1), 0);
                }
            } else {
                if (songindex > 0) {
                    songindex -= 1;
                    RecommendSongIPVkey(songindex, 0);
                } else {
                    songindex = songAttr.songlist.length;
                    RecommendSongIPVkey((songindex - 1), 0);
                }
            }
        }

        function NextSong() {
            RemoveLyricinfo();

            if (songAttr.data != undefined) {
                if ((songindex + 1) < songAttr.data.song.list.length) {
                    songindex += 1;
                    SongIPVkey(songindex, 1);
                } else {
                    songindex = 0;
                    SongIPVkey(songindex, 1);
                }
            } else {
                if ((songindex + 1) < songAttr.songlist.length) {
                    songindex += 1;
                    RecommendSongIPVkey(songindex, 1);
                } else {
                    songindex = 0;
                    RecommendSongIPVkey(songindex, 1);
                }
            }

        }

        function RemoveLyricinfo() {
            $("#SongLyric div p").remove();
            SonglrcAttr = [];
            lycinner = 0;
            $("#SongLyric div").css("transform", "translateY(" + lycinner + "px)");
        }

        function PlayMode(i) {
            //1:单曲循环 2:列表播放 3:列表循环 4:随机播放
            clearInterval(time1);
            clearInterval(time2);
            clearInterval(time3);
            audio[0].loop = false;
            if (i === 1) {
                audio[0].loop = true;
                console.log("当前模式-单曲循环");
            } else if (i === 2) {
                audio[0].loop = false;
                time1 = setInterval(LBPlayItime1, 500);
                console.log("当前模式-列表播放");
            } else if (i === 3) {
                time2 = setInterval(LBPlayItime2, 500);
                console.log("当前模式-列表循环");
            } else if (i === 4) {
                time3 = setInterval(LBPlayItime3, 500);
                console.log("当前模式-随机播放");
            }
        }

        function LBPlayItime1() {
            if (songAttr.data != undefined) {
                if (audio[0].ended) {
                    if ((songindex + 1) < songAttr.data.song.list.length) {
                        NextSong();
                    } else {
                        audio[0].pause();
                    }
                }
            } else {
                if (audio[0].ended) {
                    if ((songindex + 1) < songAttr.songlist.length) {
                        NextSong();
                    } else {
                        audio[0].pause();
                    }
                }
            }

        }


        function LBPlayItime2() {
            if (songAttr.data != undefined) {
                if (audio[0].ended) {
                    if ((songindex + 1) < songAttr.data.song.list.length) {
                        NextSong();
                    } else {
                        songindex = 0;
                        SongIPVkey(songindex, 1);
                    }
                }
            } else {
                if (audio[0].ended) {
                    if ((songindex + 1) < songAttr.songlist.length) {
                        NextSong();
                    } else {
                        songindex = 0;
                        RecommendSongIPVkey(songindex, 1);
                    }
                }
            }

        }

        function LBPlayItime3() {
            if (songAttr.data != undefined) {
                if (audio[0].ended) {
                    songindex = parseInt(Math.random(0, songAttr.data.song.list.length) *
                        (songAttr.data.song.list.length - 0));
                    SongIPVkey(songindex, 1);
                }
            } else {
                if (audio[0].ended) {
                    songindex = parseInt(Math.random(0, songAttr.songlist.length) * (songAttr.songlist.length - 0));
                    RecommendSongIPVkey(songindex, 1);
                }
            }
        }

        setInterval(function () {
                if (audio[0].readyState === 4) {
                    $("#SongTime > .SongTime").html("SongTime:" +
                        SetTimeRutrunMS(audio[0].duration)[0] +
                        ":" +
                        SetTimeRutrunMS(audio[0].duration)[1]);
                    $("#SongTime > .PlaySongTime").html("PlaySongTime:" +
                        SetTimeRutrunMS(audio[0].currentTime)[0] +
                        ":" +
                        SetTimeRutrunMS(audio[0].currentTime)[1]);
                    $("#SongProgress").css("width", (audio[0].currentTime / (audio[0].duration / 100)) + "%");


                }
            },
            30);

        setInterval(function () {


                var SongLyricp = $(\'#SongLyric > div > p\');
                if (!audio[0].paused) {
                    if (lycinner < SonglrcAttr.length - 1) {
                    } else {
                        lycinner += 1;
                        $("#SongLyric div").css("transform", "translateY(" + (-SongLyricp.height() * lycinner) + "px)");
                    }
                }

                $("#SongSpeed").change(function () {
                    audio[0].playbackRate = $(this).val();
                });
            },
            500);
    </script>
</body>
</html>

后言

最后就能实现播放了

如果觉得本技术文章对你有帮助请给我点个赞,如果有什么不足的地方,给我提意见,让我加以改进

分类:

技术点:

相关文章: