54

I am working on building a HTML5 video player with a custom interface, but I am having some problems getting the video duration information to display.

My HTML is simple:

<video id="video" poster="image.jpg" controls>     
    <source src="video_path.mp4" type="video/mp4" />
    <source src="video_path.ogv" type="video/ogg" /> 
</video>
<ul class="controls"> 
<li class="time"><p><span id="timer">0</span> of <span id="duration">0</span></p></li>  
</ul>

And the javascript I am using to get and insert the duration is

var duration = $('#duration').get(0);
var vid_duration = Math.round(video.duration);
duration.firstChild.nodeValue = vid_duration;

The problem is nothing happens. I know the video file has the duration data because if I just use the default controls, it displays fine.

But the real strange thing is if I put alert(duration) in my code like so

alert(duration);
var vid_duration = Math.round(video.duration);
duration.firstChild.nodeValue = vid_duration;

then it works fine (minus the annoying alert that pops up). Any ideas what is happening here or how I can fix it?

UPDATE: Ok so although I haven't solved this problem exactly, but I did figure out a work around that handles my biggest concern... the user experience.

First the video doesn't begin loading until after the viewer hits the play button, so I am assuming that the duration information wasn't available to be pulled (I don't know how to fix this particular issue... although I assume that it would involve just loading the video metadata separately from the video, but I don't even know if that is possible).

So to get around the fact that there is no duration data, I decided to hide the duration info (and actually the entire control) completely until you hit play.

That said, if anyone knows how to load the video metadata separately from the video file, please share. I think that should completely solve this problem.

monkey
  • 526
  • 7
  • 21
drebabels
  • 1,992
  • 3
  • 17
  • 13
  • 1
    Which browser are you using for running your HTML5? Not all browsers supports HTML5. – Buhake Sindi Feb 08 '10 at 11:29
  • 1
    I don't think it's a browser problem. I am using the latest version of Firefox / Webkit / Chrome to test it – drebabels Feb 09 '10 at 02:42
  • 1
    You can report the duration with an `X-Content-Duration` HTTP header. The browser may do a `HEAD` request to gather this information prior to downloading the video. https://developer.mozilla.org/en/Configuring_servers_for_Ogg_media – TRiG Aug 15 '11 at 14:37
  • If you do `video.load()` in the JavaScript that will at least load the metadata, but it's such an ambiguous situation. I wish you could load metadata. I'm having issues with my seeking controls. They only work if the user presses play first, cause the video to load itself and it's metadata. – Costa Michailidis Jul 03 '16 at 01:17

7 Answers7

168

Do that:

var myVideoPlayer = document.getElementById('video_player');
myVideoPlayer.addEventListener('loadedmetadata', function() {
    console.log(myVideoPlayer.duration);
});

Gets triggered when the browser received all the meta data from the video.

[edit] Since then the better approach would be to listen to 'durationchange' instead of 'loadedmetadata' which can be unreliable, as such:

myVideoPlayer.addEventListener('durationchange', function() {
    console.log('Duration change', myVideoPlayer.duration);
});
Mikushi
  • 3,311
  • 4
  • 19
  • 22
  • 8
    Instead of continuously polling as in the accepted answer this one actually gets called as soon as the video knows it has its metadata available. Much cleaner indeed. – Silvia Apr 26 '11 at 11:12
  • how would I insert the duration obtained from this into a span? – Batman Feb 14 '13 at 22:43
  • 3
    What is "myVideoPlayer" is it: var myVideoPlayer = $('#myvideo').get(0); ? – SomethingOn Mar 19 '13 at 13:07
  • 1
    I confirmed my assumption...this is what videoPlayer evaluates too and this code DOES work!! Thanks! – SomethingOn Mar 19 '13 at 13:43
  • 2
    This works great! I have a few videos on my page and I'd love to gather all the durations. Is there a way to do this dynamically (without copying the code for each video?) I am using jQuery. – Stu Jun 04 '14 at 14:27
  • 3
    It´s not working for me in chrome Version 49.0.2623.87 m. When it get´s fired, the duration still is infinity... – thetailor.de Mar 10 '16 at 13:30
  • Agreed with @thedtailer.de not working with me either on Chrome Version 45.0.2454.101 m - sometimes I get NaN, sometimes I get the actual duration. – puiu Mar 21 '16 at 19:38
  • 1
    There is, more relevantly, the `durationchange` event. – darkf May 19 '16 at 11:20
  • @Puiu See my edit for a better approach. See this JSFiddle for reference https://jsfiddle.net/a7491hjw/2/ – Mikushi May 19 '16 at 11:22
  • My readyState is 4 but still I'm not getting the duration. can you please check my question `https://stackoverflow.com/questions/52167815/html5-video-duration-infinity-while-readystate-4` – Wahid Masud Sep 04 '18 at 14:05
  • 1
    Using the `durationchange` event is, in fact, the best way to get the duration of the video cross-platform. – luisandreramos Nov 18 '21 at 12:57
32

The issue is in WebKit browsers; the video metadata is loaded after the video so is not available when the JS runs. You need to query the readyState attribute; this has a series of values from 0 to 4, letting you know what state the video is in; when the metadata has loaded you'll get a value of 1.

So you need to do something like:

window.setInterval(function(t){
  if (video.readyState > 0) {
    var duration = $('#duration').get(0);
    var vid_duration = Math.round(video.duration);
    duration.firstChild.nodeValue = vid_duration;
    clearInterval(t);
  }
},500);

I haven't tested that code, but it (or something like it) should work.

There's more information about media element attributes on developer.mozilla.org.

stopsatgreen
  • 2,062
  • 18
  • 12
  • 12
    See @Mikushi answer below for a much cleaner solution – hellosmithy Apr 22 '14 at 13:33
  • My readyState is 4 but still I'm not getting the duration. can you please check my question `https://stackoverflow.com/questions/52167815/html5-video-duration-infinity-while-readystate-4` – Wahid Masud Sep 04 '18 at 14:04
5

The HTML5 spec does allow for only preloading the metadata:

<video id="video" poster="image.jpg" controls preload="metadata">     
    <source src="video_path.mp4" type="video/mp4" />
    <source src="video_path.ogv" type="video/ogg" /> 
</video>

http://www.w3.org/TR/html-markup/video.html#video.attrs.preload

3

neither listen "loadedmetadata" or "durationchange", video.duration is unreliable.
try load "https://media.w3.org/2018/10/w3c-particles.webm"

there is a smart and effective way.

//first, seek to a big number time
video.currentTime = 7*24*60*1000;
//then listen 'seeked' event. when this event occur, that means video duration can access normally
video.onseeked = ()=>{
  alert("the duration is: "+video.duration);
  video.onseeked = undefined;
};
Kent Wood
  • 1,392
  • 2
  • 14
  • 30
  • 1
    This works for videos where the duration is not updated to an integer from inifinity no matter how much time you wait. Usually occurs for webm files. Thanks – Vaibhav Singh Nov 06 '19 at 09:49
  • I'm using webm and this was the only suggestion I could get working – wlf Mar 08 '23 at 23:40
2

This is the modification to your code

var duration = document.getElementById("duration");
var vid_duration = Math.round(document.getElementById("video").duration);
//alert(vid_duration);
duration.innerHTML = vid_duration;
//duration.firstChild.nodeValue = vid_duration;

Hope this helps.

It looks like you're using IE, why don't you use document.getElementById method to retrieve video object?

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • 1
    Hey thanks for the response. Unfortunately it doesn't work... I am still having the same issue where without calling the alert statement... the video duration just doesn't get pulled in (it just shows up as 0) And I don't really have a reason for not using getElementById... I just like jQuery selectors so I was using them. – drebabels Feb 09 '10 at 04:08
  • 1
    Well, you got 2 video sources in 1 video tag, could you put each source under 1 video tag and see if it works? – Buhake Sindi Feb 09 '10 at 08:57
0

I encountered the same problem: can not read video's duration , $('video')[0].duration always return NaN, I referred the accepted answer of @stopsatgreen and change the code to fit in a common case, it really work.

var video = $('video')[0];
var t = setInterval(function () {
    if(video.readyState > 0) {
        var duration = video.duration;
        console.log(duration);
        clearInterval(t);
    }
}, 500);

The code is very simple and really work, so I post this answer and hope it can help more people.

Kevin Yan
  • 1,236
  • 11
  • 19
0

Even though this question is tagged for Javascript, these days Typescript is pretty common so I would like to add a Typescript solution with no deprecation warnings or console errors and with a parsed minutes:seconds date display.

const video = document.getElementById('your-video-id') as HTMLVideoElement;
video?.addEventListener('loadedmetadata', () => {
const videoDuration = video.duration;
const minutes = parseInt((videoDuration / 60).toString());
const seconds =
  videoDuration % 60 < 10
    ? '0' + Math.ceil(videoDuration % 60).toString()
    : Math.ceil(videoDuration % 60).toString();
const videoDurationTime = minutes + ':' + seconds;

console.log('videoDurationTime :>> ', videoDurationTime);
});

Credits: Mikushi answer and Grepper answer

Gabriel Arghire
  • 1,992
  • 1
  • 21
  • 34