search

Home  >  Q&A  >  body text

How to get the playback duration of HTML5 audio

<p>I have an html5 <code><audio></code> tag in the page, but how do I know its duration? </p> <pre class="brush:php;toolbar:false;"><audio controls=""> <source src="p4.2.mp3"> </audio></pre> <p><br /></p>
P粉545218185P粉545218185460 days ago617

reply all(1)I'll reply

  • P粉792673958

    P粉7926739582023-08-23 11:57:19

    2020 Solution:

    When the audio metadata has not been loaded, you will get undefined or NaN (not a number). Therefore, some people recommend first using onloadedmetadata to ensure that the audio file's metadata is obtained. Also, what most people don't mention is that you have to use [0] to locate the first index of the audio DOM element, like this:

    -- Native JavaScript:

    var audio = document.getElementById('audio-1');
    audio.onloadedmetadata = function() {
      alert(audio.duration);
    };

    If this doesn't work, try the following method, but this method is less reliable and relies on the user's connection:

    setTimeout(function () {
        var audio = document.getElementById('audio-1');
        console.log("audio", audio.duration);
    }, 100);

    -- JQuery:

    $(document).ready(function() {
       var audio = $("#audio-1")[0];
       $("#audio-1").on("loadedmetadata", function() {
           alert(audio.duration);
       }); 
    });

    reply
    0
  • Cancelreply