Setting a loop range with video.js

4.1k views Asked by At

Is there a way to define a section of a video to loop with video.js? I'd like to have some sort of range control with a start and end thumb and then have the selected range loop.

2

There are 2 answers

2
Zeth On

I had to make the same thing. @phhu was close, - but there are a couple of errors in his/her suggestion.

It worked, when I adjusted the script to be this:

<script>            
    videojs('vid').ready(function () {
    this.on('timeupdate', onVideoTimeupdate );
  });
  
  function onVideoTimeupdate() {
    var loopStart = parseFloat(document.getElementById('loopStart').value);
    var loopEnd = parseFloat(document.getElementById('loopEnd').value);
    var loopEnabled = document.getElementById('loopEnabled').checked;

    if(loopEnabled){
      if (this.currentTime() < loopStart || this.currentTime() >= loopEnd ) {
        this.currentTime( loopStart );
      }
    }
  }

</script>

Update

A good comment (and Fiddle) from Phhu made me notice an error.

Here is a working Fiddle: https://jsfiddle.net/oLf7s15j/

I've updated the code as well. The problem was the initialization of the video-js element.

2
phhu On

You can use the timeupdate event to check the video's currentTime to create a basic loop, as in the example below (see live at https://jsfiddle.net/o32bku6x/)

See also loop a html5 video in specific timline with js .

<!DOCTYPE html>
<html>
    <head>
        <script src="https://vjs.zencdn.net/5.6.0/video.js"></script>
        <link href="https://vjs.zencdn.net/5.6.0/video-js.css" rel="stylesheet" />  
    </head>
    <body>

        <video id="vid" controls="controls" class="video-js">
            <source src="https://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
        </video>

        Start: <input type="text" size="5" id="loopStart" value="10" />
        End:   <input type="text" size="5" id="loopEnd"   value="15" />
        Loop:  <input type="checkbox" checked="checked" id="loopEnabled" />

        <script>            
            var vid = document.getElementById("vid");
            vid.addEventListener('timeupdate', timeupdate, false);

            function timeupdate() {
                var loopStart = parseFloat(document.getElementById('loopStart').value);
                var loopEnd = parseFloat(document.getElementById('loopEnd').value);
                var loopEnabled = document.getElementById('loopEnabled').checked;
                
                if(loopEnabled){
                    if (vid.currentTime < loopStart || vid.currentTime >= loopEnd ) {
                        vid.currentTime = loopStart;
                    }
                }
            }
        </script>

    </body>
</html>

Alternatively, you could use a plugin such as https://github.com/phhu/videojs-abloop, which adds loop controls to the player. See example at https://unpkg.com/videojs-abloop/sample/basic.html (disclaimer: I wrote this plugin)