Reputation: 659
None of those tricks works for me...
var audio=new Audio("sample.mp3");
audio.addEventListener('onreadystatechange',function({alert(audio.duration);});
if(audio.readyState===4){alert(audio.duration);}
audio.onreadystatechange=function(){alert(audio.duration);};
I want to execute alert of the audio duration when this data is available (when audio.readyState===4). Well... unless there is another magic to fetch this data as fast as possible (without using settimeout or setInterval)
Upvotes: 1
Views: 242
Reputation: 776
Why not use oncanplay
event? Something like:
var audio=new Audio("sample.mp3");
audio.oncanplay = function(){ alert(audio.duration); };
The oncanplay
event fires when enough information has been and the audio is ready to start playing.
Upvotes: 3
Reputation: 3555
Try this:
audio.addEventListener('canplaythrough', function() {
alert(audio.duration);
}, false);
Upvotes: 2
Reputation: 18764
try this:
var audio=new Audio("sample.mp3");
audio.addEventListener('onreadystatechange',alertAudio;);
function alertAudio(){
if(audio.readyState===4){
alert(audio.duration);}
}
Upvotes: 1
Reputation: 178285
You are adding event handler twice and the if needs to be inside
var audio=new Audio("sample.mp3");
audio.onreadystatechange=function(){
if(audio.readyState===4){
alert(audio.duration);
}
}
Upvotes: 1