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); }); });