javascriptfunctionaudioreadystateonreadystatechange

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)


Solution

  • 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.