Get the length of an audio:
var x = document.getElementById("myAudio").duration;
Click the button to get the exact length (duration) of the audio, in seconds.
<!DOCTYPE html> <html> <body> <audio id="myAudio" controls> <source src="sound.ogg" type="audio/ogg"> <source src="sound.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio>/*from ww w . ja v a 2 s .co m*/ <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("myAudio").duration; document.getElementById("demo").innerHTML = x; } </script> </body> </html>
The duration
property returns the length of an audio, in seconds.
This property is read-only.
If no audio is set, "NaN" (Not-a-Number) is returned.
If the audio is streamed and has no predefined length, "Inf" (Infinity) is returned.