2015-01-08 40 views
2

Youtube iframe API有檢測視頻結束的事件。如果與嵌入式播放列表一起使用,則此事件會在每個視頻之後觸發。我只想檢測播放列表中最後一個視頻的結尾。Youtube Iframe API - 檢測播放列表結尾

這是我的嘗試:

if (event.data == YT.PlayerState.ENDED && currentIndex == playlist.length - 1){ 
    alert('Playlist finished.'); 
} 

問題他這將觸發兩次。在播放列表中倒數第二個視頻結束時,播放器狀態爲ENDED,播放列表索引增加1,因此觸發得太早。它也會觸發播放列表中最後一個視頻的結尾,這是唯一預期的結果。

回答

0

我知道這是回答遲了,但我一直在尋找答案,我想出了這種笨拙的方式。

var isended=0; 
function testifover(){ 
if(isended==1) { // Did the state change while we delayed 5 seconds 
// Whatever you wanted to do at the end of the playlist here. 
} 
} 
function onPlayerStateChange(event) { 
    switch (event.data) { 
    case YT.PlayerState.UNSTARTED: 
     console.log('unstarted'); 
     break; 
    case YT.PlayerState.ENDED: 
isended=1; 
    var myVar = setTimeout(function(){testifover()} , 5000); // Delay 5 seconds to make sure we aren't loading another video 
// and then do whatever if we really are at the end of the playlist. 
     break; 
    case YT.PlayerState.PLAYING: 
    isended=0; // we started playing another vid in the playlist 
     break; 
    case YT.PlayerState.PAUSED: 
     console.log('paused'); 
     break; 
    case YT.PlayerState.BUFFERING: 
    isended=0; // we started buffering another video in the playlist 
     break; 
    case YT.PlayerState.CUED: 
     console.log('video cued'); 
     break; 
     } 
    } 

    //  On state change fires and we wait 5 seconds and make sure that hasn't changed to buffering or playing or we kill the player. 
0

只有當視頻開始播放時,您才應該設置currentIndex值。這幫助我實現了同樣的目標:

function onPlayerStateChange(event) { 

    if (event.data == YT.PlayerState.PLAYING) { 
     currentIndex = event.target.getPlaylistIndex(); 
    } 

    if (event.data == YT.PlayerState.ENDED) { 
     if (currentIndex == (playlist.length-1)) { 
      console.log('end playlist'); 
     } 
    } 
}