Moatasim Ashraf
Moatasim Ashraf

Reputation: 13

Audio duration returns NaN

I have an array of audio elements, I need to return their durations but it returns NaN!

let quran = document.querySelectorAll(".question-one audio")

console.log(quran[0].duration) // NaN ((??)
console.log(quran[0].currentTime) // 52 (works properly)

I tried a lot but a could not solve this issue, knowing that I used the same (duration) method with video elements and it worked

Upvotes: 1

Views: 249

Answers (1)

Muhammad Shoaib Raza
Muhammad Shoaib Raza

Reputation: 101

Add preload="metadata" to your tag to have it request the metadata for your audio object:

<audio controls id="testTone" preload="metadata">
    <source src="autoharp/tone0.ogg" type="audio/ogg">
</audio>
In your code, attach an event handler, to set the duration when the metadata has been loaded:

var au = document.getElementById("testTone");
au.onloadedmetadata = function() {
    console.log(au.duration)
};

Upvotes: 2

Related Questions