2016-07-28 56 views
1

我想创建一个YouTube视频播放器,每次访问网页时重新排列视频阵列,然后按照排列顺序播放它们。创建一个随机的YouTube视频播放器

到目前为止,我的代码能够从阵列中随机挑选一个视频播放它,然后随机挑选另一个视频并播放它。

问题在于视频重叠。当它随机化数组时,我希望它们都按顺序播放:如3,2,1或2,1,3或3,1,2。没有重复。

目前它将播放任何次数的任何视频。

该功能将在每次访问页面时对数组进行洗牌,此部分起作用。

function shuffle(array) { 
     var currentIndex = array.length, temporaryValue, randomIndex; 

     // While there remain elements to shuffle... 
     while (0 !== currentIndex) { 

      // Pick a remaining element... 
      randomIndex = Math.floor(Math.random() * currentIndex); 
      currentIndex -= 1; 

      // And swap it with the current element. 
      temporaryValue = array[currentIndex]; 
      array[currentIndex] = array[randomIndex]; 
      array[randomIndex] = temporaryValue; 
     } 

     return array; 
     } 

这是改编自https://developers.google.com/youtube/iframe_api_reference

// 1. This code loads the IFrame Player API code asynchronously. 
    var tag = document.createElement('script'); 

    tag.src = "https://www.youtube.com/iframe_api"; 
    var firstScriptTag = document.getElementsByTagName('script')[0]; 
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

    // 2. This function creates an <iframe> (and YouTube player) 
    // after the API code downloads. 
    var player; 
    var list = ['rgAYRbeO9GI','6wKxfH9NpVE','OJ9qLosjjH8'] 
    shuffle(list); // shuffles the array 


    function onYouTubeIframeAPIReady() { 
    player = new YT.Player('player', { 
     height: '585', 
     width: '960', 
     // videoId: list[Math.floor(Math.random() * list.length)], 
     videoId: list[0], // accesses the first index of the newly sorted list array, Ideally I want to play the next video 
     events: { 
     'onReady': onPlayerReady, 
     'onStateChange': onPlayerStateChange 
     } 
    }); 
    } 

    // 3. The API will call this function when the video player is ready. 
    function onPlayerReady(event) { 
    event.target.playVideo(); 
    } 

    // 4. The API calls this function when the player's state changes. 
    // The function indicates that when playing a video (state=1), 
    // the player should play for six seconds and then stop. 
    var done = false; 
    function onPlayerStateChange(event) { 
    if (event.data == YT.PlayerState.ENDED && !done) { // once the video is finished the onPlayerReady() function repeats. 
     onPlayerReady(); 
     done = true; 
    } 
    } 

代码,我需要一种方法来移动形成列表[0]索引到下一个,我不知道放在哪里循环。有任何想法吗?

回答

0

我设法使用此代码随机化YouTube播放列表:

var playlistLength = 198; 
function onPlayerReady(event) { 
      player.cuePlaylist({ 
      'listType': 'playlist', 
      'list': 'PLCEwouDaI4SXpFtD8wVnPY7wfx7LpXXRw', 
      'index' : [Math.floor(Math.random() * playlistLength)] 
     }); 

setTimeout(function() { 
      //event.target.stopVideo(); 
      //event.target.playVideoAt(3); 
      event.target.setShuffle(true); 
      event.target.playVideo(); 
      event.target.setLoop(true); 
      }, 
     1000); 
     }