Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a section of a youtube video on a loop?

Tags:

youtube

I am trying to make a youtube video loop at a specific section of a video.

https://www.youtube.com/v/zeI-JD6RO0k?autoplay=1&loop=1&start=30&end=33&playlist=%20zeI-JD6RO0k

From what I know:

To start and end:

start=30&end=33

To make it loop:

autoplay=1&loop=1&playlist=%20zeI-JD6RO0

The problem is that it doesn't start the next loop at the time I specify

like image 662
Tim Cooley Avatar asked Jul 28 '16 19:07

Tim Cooley


1 Answers

Note first, if one is not familiar with html or javascript beyond basics, the youtube player api link in the answer by maiermic will provide everything necessary to develop the solution provided there -on one page without a lot of skimming.

also, in case one would like to add a hh:mm:ss converter that accepts down to seconds - add / modify the code provided in the answer by maiermic with the following;

var timeStart = "HH:MM:SS";
var timeEnd = "HH:MM:SS";

var loopStart = getSeconds(timeStart);
var loopEnd =  getSeconds(timeEnd);

var section = {
  start: loopStart,
  end: loopEnd
};

and add the function;

function getSeconds(str) {
    var p = str.split(':'),
    s = 0, m = 1;

    while (p.length > 0) {
        s += m * parseInt(p.pop(), 10);
        m *= 60;
    }

    return s;
}

And in the case one would like to include slower playback up to normal speed with this code, alter the following function with

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
        var duration;

        var playerSpeed = player.getPlaybackRate();

        if (playerSpeed == .25)
            duration = (section.end - section.start) * 4;
        else if (playerSpeed == .5) 
            duration = (section.end - section.start) * 2;
        else if (playerSpeed == .75) 
            duration = (section.end - section.start) * 1.5;
        else if (playerSpeed == 1) 
            duration = (section.end - section.start);

        setTimeout(restartVideoSection, duration * 1000);
    }
  }

as well as

    function onPlayerReady(event) {
        player.seekTo(section.start);
        player.setPlaybackRate(.25);     // choose .25, .50, .75, or 1
        player.playVideo();
    }

Of course, you will have to modify the video id/ HH:MM:SS fields in the code every time you want a different video / section of video. Additionally, if one chooses to include support for variable player speed as above, those values will have to be added as desired. The playback speed can be altered via the player buttons once started if the code above is included, but if it is changed during play back, the duration will not refresh until the video begins at the start again.

like image 195
kjp Avatar answered Oct 16 '22 20:10

kjp