Search code examples
javascripthtmlhtml5-videohtml5-audio

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


Solution

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