Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Video duration without playing video

I am trying to get video duration in HTML5 with out playing video or before playing video to show on video thumb as you seen on you tube or any other video sites.

Any help will be really appreciate.

Thanks in Advance.

like image 764
Sajal Avatar asked Oct 25 '13 14:10

Sajal


People also ask

How do I find the length of a video in HTML?

The duration property returns the length of the current audio/video, in seconds. If no audio/video is set, NaN (Not-a-Number) is returned.

Can HTML5 be video?

HTML5 is the latest version of HTML. Unlike previous versions of HTML, HTML5 enables developers to easily add video to webpages with a video tag.

What is the correct HTML5 element for playing video files?

<video>: The Video Embed element. The <video> HTML element embeds a media player which supports video playback into the document.

How do I stop videos from playing in HTML?

The pause() method halts (pauses) the currently playing audio or video.


2 Answers

For HTML5 you should be able to use the video tag's duration property, once the file's metadata is loaded. See this answer for a good way to do it:

Retrieving HTML5 video duration separately from the file

To quote the anwser by Mikushi:

myVideoPlayer.addEventListener('loadedmetadata', function() {
    console.log(videoPlayer.duration);
});

By listening for the 'loadedmetadata' event you will ensure the duration value has been loaded.

More details on the loadedmetadata can be found here: http://www.w3schools.com/tags/av_event_loadedmetadata.asp

EDIT

As per @lucas-vasques 's comment, instead of the loadmetadata event, you could use durationchange which the MDN Media Events list describes as ...

The metadata has loaded or changed, indicating a change in duration of the media. This is sent, for example, when the media has loaded enough that the duration is known.

like image 180
ToddBFisher Avatar answered Oct 23 '22 01:10

ToddBFisher


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function getDuration() {
            var s = document.getElementById('a');
            alert(s.duration)
        }
    </script>
</head>
<body>
<div>
    <video src="2.mp4" id="a" controls="controls"></video>
    <button onclick="getDuration()">get duration</button>
</div>
</body>

</html>
like image 3
Vicky Gonsalves Avatar answered Oct 23 '22 01:10

Vicky Gonsalves