Play an HTML 5 video tag fragment with video.playFragment()
14/10/2019 by Capy

Front.id

In some special cases wou need to play a video fragment from a specific time to a specific time.

This is not easy since there is no an official video api method for that. 

For this reason I created this HTMLVideoElement prototype called playFragment()

/**
 * Plays a video fragment.
 *
 * @param {Number} from The time video where to start. 
 * If this param is null the video will be played from the current position.
 * @param {Number} to The time video where to stop.
 * @param {Number} frameRate The video framerate.
 * @param {Function} cb Callback launched after fragment is played. Optional.
 */
HTMLVideoElement.prototype.playFragment = function (from, to, frameRate, cb) {
  if (playing) return;
  const video = this;
  video.currentTime = from === null ? video.currentTime : from;
  video.play();

  const timeCheck = setInterval(function () {
    if (video.currentTime >= to) {
      clearInterval(timeCheck);
      video.pause();
      playing = false;
      typeof cb === 'function' && cb();
    }
  }, 1000 / frameRate);
};

It's really simple to use:

const video = document.getElementsByTagName("video");

video.playFragment(1.2, 6.3, 25);

At example "1.2" is the start time in seconds, "6.3" is the end time in seconds and "25" is the original video frame rate (needed for the calcs).

Sample

Here is a live sample where I created a video with different positions of a box. When the user clicks "next" or "prev" I use video.playFragment() to play the right fragment of the video to make a "video-slider":

See the Pen HTML 5 video.playFragment() by Marcelo Tosco (@capynet) on CodePen.

Add new comment

The content of this field is kept private and will not be shown publicly.

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.