Search code examples
javascripthtml

How to extract duration of a video from a link


I am displaying a video on my website like this:

<video>
    <source src={link} type="video/mp4" />
</video>

And I would like to extract duration of the video from the provided src link, to display it somewhere else on the page. Assume we have the link stored as a string, how will I extract the duration of the video?

Sample src link: https://firebasestorage.googleapis.com/v0/b/qriositynet-dev.appspot.com/o/chat%2FMgttfKqKIDhQ6bgtgy6V%2Fvideos%2F1663229371400watermelon-bunny.mp4?alt=media&token=722bb260-c65b-46fe-8805-4a5a742f282d


Solution

  • to get the duration of the video you have to wait for it to load using the event listener and that way you are sure you have the data, this is a link you can use to help you learn more about the API, here.

    let video = document.getElementById("video")
    
    video.addEventListener('loadeddata', function() {
        console.log("test", video.duration)
       // Video is loaded and can be played
    }, false);
    
    
        
    function myFunction() { 
      alert(video.duration);
    } 
    
    myFunction
    <html>
    <h1>video duration</h1>
    <button onclick="myFunction()" type="button">Get video length</button><br>
    
    <video id="video">
        <source src="https://firebasestorage.googleapis.com/v0/b/qriositynet-dev.appspot.com/o/chat%2FMgttfKqKIDhQ6bgtgy6V%2Fvideos%2F1663229371400watermelon-bunny.mp4?alt=media&token=722bb260-c65b-46fe-8805-4a5a742f282d" type="video/mp4" />
    </video></html>