Is there a way to use the Youtube API to play a video until a certain point in the video and then pause it?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With