如何使用javascript在播放列表中加载第一个视频

时间:2013-10-26 17:58:57

标签: javascript jquery video youtube youtube-javascript-api

我正在使用tubeplayer插件为我的热门100音乐排行榜网站http://beta.billboard.fm生成视频播放列表。

我提取播放列表数据并根据该数据生成视频播放列表。问题是我目前在主页上手动输入youtube视频ID以获取初始视频加载视频,我想在其中创建一个变量,动态提取第一个youtube视频ID并在initialVideo之后插入

所以我试图创建一个变量,从我可以放入标准插件参数的热门100年播放列表中拉出#1轨道:

我将其定义为var initialVideoID =

<script>
// IE workaround
function JSONQuery(url, callback) {
    if ($.browser.msie && window.XDomainRequest) {

        // alert('ie');    
        // var url =  "http://gdata.youtube.com/feeds/api/videos?q=cher&category=Music&alt=json";

        // Use Microsoft XDR
        var xdr = new XDomainRequest();
        xdr.open("get", url);

        xdr.onerror = function () {
            console.log('we have an error!');
        }
        xdr.onprogress = function () {
            // console.log('this sucks!');
        };
        xdr.ontimeout = function () {
            console.log('it timed out!');
        };
        xdr.onopen = function () {
            console.log('we open the xdomainrequest');
        };
        xdr.onload = function () {
            // XDomainRequest doesn't provide responseXml, so if you need it:
            var dom = new ActiveXObject("Microsoft.XMLDOM");
            dom.async = true;
            dom.loadXML(xdr.responseText);
            // alert(xdr.responseText);

            callback(jQuery.parseJSON(xdr.responseText));
            // alert(data.feed.entry[0].media$group.media$content[0].url);
            // alert("ie");
        };

        xdr.send();

    } else {
        $.getJSON(url, callback);
    }
};

var yearMap = [];

createYearMap();

function createYearMap() {
    yearMap["1940"] = [1946, 1947, 1948, 1949];
    yearMap["2010"] = [2010, 2011, 2012];

    for (var i = 195; i < 201; i++) {
        var curDecade = i * 10;
        yearMap[curDecade.toString()] = [];
        for (var j = 0; j < 10; j++) {
            yearMap[curDecade][j] = curDecade + j;
        }
    }
}

// console.log(yearMap["2010"]);

(function ($) {
    $(window).ready(function () {

        // alert("before get");
        // $.get("test.htm", function(data) {
        //     // var fileDom = $(data);
        //     // alert("get callback");
        //     $("#jqueryTest").html(data);

        // });
        // setInterval(function(){alert("Hello")},3000);

        $(".song-description").mCustomScrollbar();


        // var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" +"pink floyd" + "&track=" + "money" + "&format=json";

        // JSONQuery(url, function(data) {
        //   if (data.track) {
        //     if (data.track.wiki) {
        //       $("#song-info").html(data.track.wiki.summary);
        //     } else {
        //       $("#song-info").html("No song info found");
        //     }
        //   } else {
        //     $("#song-info").html("No song info found");
        //     console.log("artist not found");
        //   }
        //   $(".song-description").mCustomScrollbar("update");  
        // });


        // $("#example tbody tr").click(function() {
        //   selectPlaying(this, true);
        // });

        jQuery(".youtube-video").tubeplayer({
            width: 300, // the width of the player
            height: 225, // the height of the player
            allowFullScreen: "true", // true by default, allow user to go full screen
            initialVideo: var initialvideoID, // the video that is loaded into the player
            preferredQuality: "default", // preferred quality: default, small, medium, large, hd720
            showinfo: true, // if you want the player to include details about the video
            modestbranding: true, // specify to include/exclude the YouTube watermark
            wmode: "opaque", // note: transparent maintains z-index, but disables GPU acceleratio
            theme: "dark", // possible options: "dark" or "light"
            color: "red", // possible options: "red" or "white"
            onPlayerEnded: function () {
                    videoEnded();
                },
                onPlayerPlaying: function (id) {
                    setIconToPause();
                }, // after the play method is called
                onPlayerPaused: function () {
                    setIconToPlay();
                }, // after the pause method is called
                onStop: function () {}, // after the player is stopped
                onSeek: function (time) {}, // after the video has been seeked to a defined point
                onMute: function () {}, // after the player is muted
                onUnMute: function () {} // after the player is unmuted
        });
        setInterval(function () {
            updateProgressBar()
        }, 1000);

        loadPlaylist("hot100", true);
    });
})(jQuery);

var initialvideoID = "yyDUC1LUXSU"

    function videoEnded() {
        nextVideo();
    }

var intervalTimer;

function startPlayer() {
    jQuery(".youtube-video").tubeplayer("play");
    playing = true;

    clearInterval(intervalTimer);
    intervalTimer = setInterval(function () {
        updateProgressBar()
    }, 1000);

    setIconToPause();
}

function setIconToPause() {
    var button = $(".icon-play");

    if (button) {
        button.removeClass("icon-play")
        button.addClass("icon-pause");
    }
}

function setIconToPlay() {
    var button = $(".icon-pause");

    if (button) {
        button.removeClass("icon-pause")
        button.addClass("icon-play");
    }
}

function pausePlayer() {
    jQuery(".youtube-video").tubeplayer("pause");
    playing = false;

    clearInterval(intervalTimer);
    setIconToPlay();
}

function selectPlaying(item, autoStart) {
    var nowPlayingItem = $(".nowPlaying");

    if (nowPlayingItem) {
        nowPlayingItem.removeClass("nowPlaying");
    }

    $(item).addClass("nowPlaying");

    var aPos = $('#example').dataTable().fnGetPosition(item);
    var aData = $('#example').dataTable().fnGetData(aPos);

    if (aData[3]) {

        // $("#song-info").html("Loading song info...");
        $("#song-info").html("");


        var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" + aData[1] + "&track=" + aData[2] + "&format=json";

        JSONQuery(url, function (data) {
            if (data.track) {
                if (data.track.wiki) {
                    $("#song-info").html(data.track.wiki.summary);
                } else {
                    $("#song-info").html("No song info found");
                }
            } else {
                $("#song-info").html("No song info found");
                console.log("artist not found");
            }
            // $(".song-description").mCustomScrollbar("update");  
        });

        $(".info-rank").html("#" + aData[0]);
        $(".info-artist").html(aData[1]);
        $(".info-song").html(aData[2]);
        $(".info-year").html($("#navYear").html());

        var ytId = aData[3];
        if (autoStart) {
            jQuery(".youtube-video").tubeplayer("play", ytId);
            setIconToPause();
        } else {
            jQuery(".youtube-video").tubeplayer("cue", ytId);
            setIconToPlay();
        }
        clearInterval(intervalTimer);
        intervalTimer = setInterval(function () {
            updateProgressBar()
        }, 1000);
        playing = true;
        // alert("youtube video id is: " + ytId);
    } else {
        alert("no youtube id");
    }
}


function previousVideo() {
    var curPlaying = $(".nowPlaying")[0];
    var nextItem;
    if (curPlaying) {
        nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, false);
        if (!nextItem) {
            nextItem = $('#example').dataTable().fnGetNodes($('#example').dataTable().fnSettings().fnRecordsTotal() - 1);
        }
    } else {
        nextItem = $('#example').dataTable().fnGetNodes(0);
    }
    selectPlaying(nextItem, true);
}

function nextVideo() {
    var curPlaying = $(".nowPlaying")[0];
    var nextItem;
    if (curPlaying) {
        nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, true);
        if (!nextItem) {
            nextItem = $('#example').dataTable().fnGetNodes(0);
        }
    } else {
        nextItem = $('#example').dataTable().fnGetNodes(0);
    }
    selectPlaying(nextItem, true);
}

function updateProgressBar() {
    // console.log("update bar");
    myData = jQuery(".youtube-video").tubeplayer("data");
    // console.log("update progress bar: " + (myData.currentTime / myData.duration * 100) + "%");
    $(".bar").width((myData.currentTime / myData.duration * 100) + "%");
}

var playing = false;

function playPauseClick() {
    if (playing) {
        pausePlayer();
    } else {
        startPlayer();
    }
}

function loadPlaylist(year) {
    loadPlaylist(year, false);
}


function loadPlaylist(year, cueVideo) {
    $.get("playlist/" + year + "playlist.txt", function (data) {
        // var fileDom = $(data);
        // alert("get callback");
        // $("#playlistContents").html(data);
        // $('#example').dataTable().fnAddData(data);
        // var obj = eval("[[1,2,3],[1,2,3]]");
        // obj = eval(data.toString());
        obj = $.parseJSON(data);
        // console.log(obj);
        $('#example').dataTable().fnClearTable();
        $('#example').dataTable().fnAddData(obj);
        // $("#example tbody tr").click(function() {
        //   selectPlaying(this, true);
        // });

        if (year == "hot100") {
            $("#navYear").html("Weekly Hot 100");
            $("#navYearLabel").hide();
        } else {
            $("#navYear").html(year);
            $("#navYearLabel").show();
        }

        if (cueVideo) {
            selectPlaying($('#example').dataTable().fnGetNodes(0), false);
        }
        // $('#example').dataTable().fnAddData(data);
    });
}

function modalDecadeClick(decade) {
    var string = "";

    if (decade == 'hot100') {
        loadPlaylist("hot100");
        $('#modal-example-decade').modal('hide');
        $('#modal-year').modal('hide');
    } else {

        for (var i = 0; i < yearMap[decade].length; i++) {
            string += '<a href="#" onclick="modalYearClick(this)"><li>' + yearMap[decade][i] + '</li></a>';
        }

        $('#modal-example-decade').modal('hide');
        $('#specific-year-list').empty();
        $('#specific-year-list').html(string).contents();
    }
}

function modalYearClick(node) {
    var year = parseInt($(node).children("li").html());
    // console.log($(node).children("li").html());
    $('#modal-year').modal('hide');
    loadPlaylist(year);
}

function progressBarClick(e) {
    var seekPercent = (e.pageX - $(".progress:first").offset().left) / $(".progress:first").width();

    var seekTime = jQuery(".youtube-video").tubeplayer("data").duration * seekPercent;

    jQuery(".youtube-video").tubeplayer("seek", seekTime);
}

var minYear = 1946;
var maxYear = 2012;

function nextYear() {
    var year = $("#navYear").html();

    if (year == "Weekly Hot 100") {
        alert("Max year is " + maxYear);
        return;
    }

    year = parseInt($("#navYear").html());

    year++;
    if (year > maxYear) {
        loadPlaylist("hot100");
        return;
    }
    loadPlaylist(year);
}

function prevYear() {
    var year = $("#navYear").html();

    if (year == "Weekly Hot 100") {
        loadPlaylist(2012);
        return;
    }

    year = parseInt($("#navYear").html());

    year--;
    if (year < minYear) {
        alert("Min year is " + minYear);
        return;
    }
    loadPlaylist(year);
}

function closeFilter() {
    toggle_visibility('toggle-filter');

    var oTable = $('#example').dataTable();

    // Sometime later - filter...
    oTable.fnFilter('');
}
</script>

0 个答案:

没有答案