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).
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