2

Youtube iframe API has an event for detecting the end of a video. If used with an embedded playlist, this event fires after every video. I wish to only detect the end of the last video in a playlist.

This is my attempt:

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

The problem his this will trigger twice. At the end of the second to last video in the playlist, the player state is ENDED and the playlist index increases by one, thus triggering too early. It also triggers at the end of the last video in the playlist which is the only intended result.

4

2 回答 2

1

您应该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');
        }
    }
}
于 2016-06-13T14:53:46.997 回答
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.
于 2015-11-08T13:33:13.913 回答