Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio duration returns NaN

Accessing an HTML5 audio element (a .ogg file) with JavaScript in Chrome. The file does play properly, yet somehow it will not recognize the duration.

I just cribbed this code: https://www.w3schools.com/jsref/prop_audio_duration.asp (I know w3schools isn't great, but it seems like something else is the problem...)

var x = document.getElementById("testTone").duration;
console.log("duration:"+x);  // duration:NaN

var y = document.getElementById("testTone");
y.play();   // works!

the element...

<audio controls id="testTone">
    <source src="autoharp/tone0.ogg" type="audio/ogg">
</audio>
like image 527
drenl Avatar asked Jun 17 '17 23:06

drenl


People also ask

How to get the duration of the Audio in HTML?

The duration property returns the length of the current audio/video, in seconds. If no audio/video is set, NaN (Not-a-Number) is returned. Note: This property is read-only.

What is duration in audio?

"Duration is the length of time a pitch, or tone, is sounded." A note may last less than a second, while a symphony may last more than an hour. One of the fundamental features of rhythm, or encompassing rhythm, duration is also central to meter and musical form.


1 Answers

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)
};
like image 115
ugh StackExchange Avatar answered Sep 18 '22 10:09

ugh StackExchange