Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a way to use the Youtube API to play a video until a certain point in the video and then pause it?

like image 663
Mason Avatar asked Jan 04 '13 06:01

Mason


2 Answers

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.

like image 80
thirdender Avatar answered Nov 14 '22 21:11

thirdender


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);
like image 22
Nippey Avatar answered Nov 14 '22 21:11

Nippey