Youtube API SeekTo() and Stop() on specific timepoint

4.2k Views Asked by At

I want to play specific points in a Youtube video. Is there a possibility to stop a video on a certain timepoint with the YouTube javascipt API or maybe with another video website as Vimeo?

I can now say (pseudocode)

PlayFragment(start, stop){
    player.seekTo(40);
    player.stop();
}

But I want to stop at for example point 60, to show only the fragment of 20 seconds.

Is there any possibility for this. Or maybe using onStateChange or another trigger when video is on certain timepoint?

2

There are 2 best solutions below

1
On BEST ANSWER

There looks like there is, check out this link for 'YouTube JavaScript API Reference'

https://developers.google.com/youtube/js_api_reference

PlayFragment(start, stop){
player.seekTo(40);

while(player.getCurrentTime() !> 60)
{
     sleep(1000);
}

player.stop();
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
0
On

Typically I'd set an interval, then check "has the timestamp passed 60 since last time? if so, stop"

There's also a "start and end" option you can put in the URL itself which may be useful...