Hezi-Gangina
Hezi-Gangina

Reputation: 659

How to execute alert of the audio duration when data is available?

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

Answers (4)

Niro
Niro

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

martinezjc
martinezjc

Reputation: 3555

Try this:

audio.addEventListener('canplaythrough', function() { 
   alert(audio.duration);
}, false);

Upvotes: 2

maioman
maioman

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

mplungjan
mplungjan

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

Related Questions