1

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)

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Hezi-Gangina
  • 637
  • 6
  • 20

4 Answers4

3

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.

Niro
  • 776
  • 8
  • 15
2

Try this:

audio.addEventListener('canplaythrough', function() { 
   alert(audio.duration);
}, false);
martinezjc
  • 3,415
  • 3
  • 21
  • 29
1

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);
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

try this:

var audio=new Audio("sample.mp3");

audio.addEventListener('onreadystatechange',alertAudio;);

function alertAudio(){
if(audio.readyState===4){
 alert(audio.duration);}
 }
maioman
  • 18,154
  • 4
  • 36
  • 42