Reputation: 1333
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>
Upvotes: 11
Views: 22201
Reputation: 1
function getDuration(){
let au = document.createElement('audio'), inp = document.getElementById('UploadInput');
if (inp.value) {
if (inp.files[0].type.match(/audio|video/g)) {
au.src = URL.createObjectURL(inp.files[0])
au.setAttribute('preload', "metadata")
au.addEventListener('loadedmetadata', () => {
console.log(`Duration: ~ ${au.duration.toFixed()}s`)
})
// document.body.appendChild(au)
} else {
console.log('File is not Audio/Video');
}
} else {
console.log('No File Dropped!');
}
}
<input id=UploadInput type=file onchange="getDuration();">
Upvotes: 0
Reputation: 1
you can try this..hope it will work i used this in 'timeupdate' event as i was getting same NaN error.
var x = document.getElementById("testTone").duration;
if(x){
console.log("duration:"+x);
}
Upvotes: 0
Reputation: 11342
Beside @FrankerZ's solution, you could also do the following:
<audio controls id="testTone">
<source src="https://www.w3schools.com/jsref/horse.ogg" type="audio/ogg">
<source src="https://www.w3schools.com/jsref/horse.mp3" type="audio/mpeg">
</audio>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("testTone").duration;
console.log("duration:" + x); // duration:NaN
var y = document.getElementById("testTone");
y.play(); // works!
}
</script>
Upvotes: 0
Reputation: 22911
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: 28