HTML5 Video duration without playing video

前端 未结 4 1562
不思量自难忘°
不思量自难忘° 2020-12-03 10:43

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.

An

相关标签:
4条回答
  • 2020-12-03 11:12

    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.

    0 讨论(0)
  • 2020-12-03 11:21

    There is a special event triggered on video elements called "loadedmetadata". Once this one is triggered, properties such as duration are available on the video element.

    Here's an exhaustive list of all HTML5 video events : http://www.w3.org/2010/05/video/mediaevents.html

    0 讨论(0)
  • 2020-12-03 11:32
    <!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>
    
    0 讨论(0)
  • 2020-12-03 11:32
    // Assume "video" is the video node
    var i = setInterval(function() {
        if(video.readyState > 0) {
            var minutes = parseInt(video.duration / 60, 10);
            var seconds = video.duration % 60;
    
            // (Put the minutes and seconds in the display)
    
            clearInterval(i);
        }
    }, 200);
    
    0 讨论(0)
提交回复
热议问题