Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control start position and duration of play in HTML5 video

We have a video (13 minutes long) which we would like to control using HTML5. We want to be able to let our users control and select the parts of the video they want to play. Preferably this control would be through 2 input fields. They would input start time (in seconds) in first box and input duration to play (in seconds) in second box. For example, they might want to start the video 10 seconds in and play for 15 seconds. Any suggestions or guidance on the Javascript needed to do this?

Note: I have found the following:

  • Start HTML5 video at a particular position when loading?

But it addresses only starting at a particular time, and nothing with playing the video for a specified length of time.

like image 673
Cole Hudson Avatar asked Jun 26 '12 17:06

Cole Hudson


3 Answers

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();
  }
});
like image 85
Paul Sham Avatar answered Nov 15 '22 15:11

Paul Sham


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.

like image 34
Jim S. Avatar answered Nov 15 '22 16:11

Jim S.


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.

like image 21
Arvin Avatar answered Nov 15 '22 17:11

Arvin