How to seek to a timestamp in a video without loading the whole thing? (HTML5)

Viewed 27

I'm writing an application in which users need to skip to sections of videos. The code below works but is very slow because the video loads from the beginning. Is there a way to skip to a section of a video without loading it from the beginning?

Can this be done purely on the client side with javascript or do I need to implement a custom back end solution as well?

<video id="video1" src="video.mov" type="video/quicktime" controls></video>

<button onclick="setCurTimeVideo(92)" type="button" value="92"> Skip to 1:32 </button>

<script>        
      var vid1 = document.getElementById("video1");

      function setCurTimeVideo(value) {
        vid1 = document.getElementById("video1");
        vid1.currentTime = value;
      };
</script>
2 Answers

You ask if you can do what you are targeting just on the client side - the answer is generally yes.

The reason for saying 'generally' is that you need a couple of things on the server side also:

  • The video must be in a format where it is possible to load some header information and then decode and play back just the part you want without having to decode the whole file.
  • The server must be able to serve 'portions' or ranges of the files and not just the entire file.

Almost all common video formats you will stream support the first requirement and most servers support 'range requests', and/or a dedicated chunked streaming protocol like HLS or DASH to support the second requirement. If you are not using HLS or DASH you may need to check that your server is configured to support range requests.

Check out this SO question and this jsfiddle! I suggest to make sure the video is paused before updating the time, like so:

function setCurTimeVideo(value) {
    vid1.play();
    vid1.pause();
    vid1.currentTime = value;
    vid1.play();
}
Related