2016-07-28 57 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); 
     }