Infinity Audio/Video Duration Issue Fixed Using JavaScript

In this article, we will learn how to fix the Infinity Audio/Video duration issue using JavaScript.

We can use the duration property to get the length of the current Audio/Video in seconds. Unfortunately, with some Audio/Video we will see the duration as Infinity. A chrome bug that causes the duration not to be available under certain circumstances. The issue is in WebKit browsers, the metadata is loaded after the Audio/Video. So the duration is not available when the JS runs.

To solve this issue we just have to use addEventListener as given below.

<!DOCTYPE html>
<html>
<body>
    <video src="myVideo.mp4" id="myVideo" height="200" width="400" controls>
        Your browser does not support HTML5 video.
    </video>
    <button onclick="getVideoDuration()" type="button">Get Video Duration</button>
    <script>
        var vid = document.getElementById("myVideo");
        vid.addEventListener('loadedmetadata', function () {
            if (vid.duration == Infinity) {
                vid.currentTime = 1e101;
                vid.ontimeupdate = function () {
                    this.ontimeupdate = () => {
                        return;
                    }
                    vid.currentTime = 0;
                    return;
                }
            }
        });
        function getVideoDuration() {
            alert(vid.duration);
        }
    </script>
</body>
</html>

Output:

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check Download Files In ZIP Format In Angular 9

7 Comments

  1. Flora

    Thanks!

    0
    0
    Reply
  2. Wendell

    Thanks!!!!!!!!!!

    0
    0
    Reply
    1. You’re welcome.

      0
      0
      Reply
  3. Venkatesh

    Thanks a lot.I have finally fixed with this hack. You saved me.

    0
    0
    Reply
    1. You’re welcome.

      0
      0
      Reply
      1. BaBa

        Any idea how can I get the duration in reacting with blob object URL?

        0
        0
        Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories