How to get the playback duration of HTML5 audio
P粉545218185
2023-08-22 21:19:42
<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>
2020 Solution:
When the audio metadata has not been loaded, you will get
undefined
orNaN
(not a number). Therefore, some people recommend first usingonloadedmetadata
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:
If this doesn't work, try the following method, but this method is less reliable and relies on the user's connection:
-- JQuery: