Control start position and duration of play in HTML5 video

泪湿孤枕 提交于 2019-11-30 13:16:59

You could use the timeupdate event listener.

Save the start time and duration time to variable after loadedmetadata event.

// Set video element to variable
var video = document.getElementById('player1');

var videoStartTime = 0;
var durationTime = 0;

video.addEventListener('loadedmetadata', function() {
  videoStartTime = 2;
  durationTime = 4;
  this.currentTime = videoStartTime;
}, false);

If current time is greater than start time plus duration, pauses the video.

video.addEventListener('timeupdate', function() {
  if(this.currentTime > videoStartTime + durationTime){
    this.pause();
  }
});
Arvin

If you are able to set start time and end time of video while setting the video url. you can specify the start and end time in the url itself like

src="future technology_n.mp4#t=20,50"

it will play from 20th second to 50th second.

There are a lot of nuances to using the javascript solution proposed by Paul Sham. A much easier course of action is to use the Media Fragment URI Spec. It will allow you to specify a small segment of a larger audio or video file to play. To use it simply alter the source for the file you are streaming and add #t=start,end where start is the start time in seconds and end is the end time in seconds.

For example:

var start = document.getElementById('startInput').value;
var end = document.getElementById('endInput').value;

document.getElementById('videoPlayer').src = 'http://www.example.com/example.ogv#t='+start+','+end;

This will update the player to start the source video at the specified time and end at the specified time. Browser support for media fragments is also pretty good so it should work in any browser that supports HTML5.

Extend to michael hanon comments: IE returns buffered.length = 0 and seekable.length = 0. Video doesn't play. So solution:

src="video.mp4#t=10,30"

will not works in IE. If you would like to support IE only way is to use javascript to seek video just after start from 0 second.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!