How to get the playback duration of HTML5 audio
P粉545218185
P粉545218185 2023-08-22 21:19:42
0
1
609
<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粉545218185
P粉545218185

reply all(1)
P粉792673958

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);
   }); 
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template