监控YouTube视频播放时间

时间:2015-05-18 10:22:35

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

我在HTML网页上的iframe中有一个YouTube视频。 当youtube视频播放达到5秒时,我想发一些事件。

我正在使用youtube api的player.getCurrentTime()方法。

HTML code:

<div><iframe id="frameID" width="640" height="390" frameborder="0" title="YouTube video player" type="text/html" src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe></div>

JS:

var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('frameID', {
    events: {
        'onReady': onPlayerReady,
        'onStateChange': stateChange
    }
});
}
var playedFirstTime=0; //to check if the video is played first time
function stateChange(evt) {

         if (evt.data == YT.PlayerState.PLAYING && playedFirstTime==0) {
             playedFirstTime=1
        timestampReached(); //if video is played first time then call the method.
    }

};
function timestampReached()
{

   var myVar= setInterval(function(){   
   if(player.getCurrentTime()>5)   //checking the current time after each second
   {
       alert("reached");
       clearInterval(myVar);

   }
},1000);

}

function onPlayerReady(event) {

//    timestampReached();
}

目前,如果视频播放达到5秒,我将显示警告框。

上面的代码工作正常,但问题是,我在这里检查每秒后的当前时间,直到5秒(如果视频在5秒之前暂停,则更多)。这增加了开销。我想要的是,某种方式可以在指定的时间过后调用回调方法,我不需要连续检查时间。

0 个答案:

没有答案
相关问题