I am trying to get the audio duration using jQuery but having hard time getting it. The method I am using is defined below
var audioElement = document.createElement('audio');
audioElement.setAttribute('src','song.mp3');
audioElement.play();
var duration = audioElement.duration;
$(".songtime").html(duration);
But it says nan
Does anybody have any idea how to solve this?
Since the audio isn't still loaded, you need to wait until your element has the metadata loaded, there is a simple way to do it:
audioElement.addEventListener("loadedmetadata", function(_event) {
var duration = audioElement.duration;
//TODO whatever
});
Probably issue is not valid any more but issue is that audio doesnt load file yet. You should add event when file is loaded
$(audioElement).on("canplay", function () {
alert(this.duration);
});
You are trying to read the duration before the audio file has been loaded. You have to wait until the browser knows what the duration is (i.e. after it has had time to download the file header).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With