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)

4

4 回答 4

3

为什么不使用oncanplay事件?就像是:

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

audio.oncanplay = function(){ alert(audio.duration); };

oncanplay当有足够的信息并且音频准备好开始播放时,该事件会触发。

于 2015-04-29T20:14:16.363 回答
2

尝试这个:

audio.addEventListener('canplaythrough', function() { 
   alert(audio.duration);
}, false);
于 2015-04-29T20:09:20.323 回答
1

您要添加两次事件处理程序,并且 if 需要在里面

var audio=new Audio("sample.mp3");
audio.onreadystatechange=function(){
  if(audio.readyState===4){     
    alert(audio.duration);
  }
}
于 2015-04-29T20:08:48.003 回答
1

尝试这个:

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

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

function alertAudio(){
if(audio.readyState===4){
 alert(audio.duration);}
 }
于 2015-04-29T20:09:58.147 回答