Use YoutubeAPI to play youtube video until a particular time and pause

让人想犯罪 __ 提交于 2019-12-04 09:26:22

I've modified the code from the YouTube Player API Reference for iframe Embeds to pause play after a certain number of seconds.

Demo

The code works by waiting for the onPlayerStateChange event. When the event fires, it checks the event to see if it's a PLAYING event. If it is, it calculates the remaining time from the current time (getCurrentTime() method) to the desired pause point (hardcoded as the stopPlayAt variable). It sets a Javascript timer to wait that difference and then pass the API a command to pause the video.

You can use the command cueVideoById in Object syntax to achieve this.

See here: https://developers.google.com/youtube/iframe_api_reference#cueVideoById

This is the way it should look like to start a video like this.

//Minimal Example
player.cueVideoById({videoId:String, endSeconds:Number});
player.playVideo();

EDIT: The above sample stops the video. If you want to pause it, a little more action is required by the JavaScript code.

In detail, you have to poll for the right time.

function checkTime() {
   if ( player.getCurrentTime() == finishTime )
      player.pauseVideo()
   else
      setInterval(checkTime, 500);
}

checkTime();

Or keep track of the time in JS:

var duration = finishTime - player.getCurrentTime();
player.playVideo()
setInterval("player.pauseVideo();", duration*1000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!