Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  183] [ 7]  / answers: 1 / hits: 18312  / 7 Years ago, sat, june 17, 2017, 12:00:00

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>

More From » audio

 Answers
13

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

[#57406] Thursday, June 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
desiraeleandrah

Total Points: 202
Total Questions: 111
Total Answers: 115

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
desiraeleandrah questions
Thu, Nov 19, 20, 00:00, 4 Years ago
Wed, Nov 11, 20, 00:00, 4 Years ago
Wed, Oct 14, 20, 00:00, 4 Years ago
;