2015-02-07 105 views
2

我試圖確定何時HTML5音頻元素已準備好開始播放,因此我可以通知用戶。我正在使用以下代碼:`canplay` HTML5音頻事件未觸發

<script type="text/javascript"> 
    var audio = document.getElementById("audio") 
</script> 

<audio id="audio" hidden loop> 
<source src="/static/music/music.mp3" type="audio/mpeg"> 
<source src="/static/music/music.ogg" type="audio/ogg"> 
<source src="/static/music/music.wav" type="audio/wav"> 
No support for HTML5 audio! 
</audio> 

<div id="playButton" onclick="audio.play();audio.addEventListener('canplay',function() { 
    alert("ready!"); 
});">PLAY</div> 

但是,即使在按下playButton之後警報也不會出現。我使用lates Chrome(Chrome 40)

+0

希望它會幫助你:) http://stackoverflow.com/questions/10790091/html5-audio-events-not-triggering-on-chrome – 2015-02-07 07:25:30

回答

2

在JavaScript發現之前,您正在獲取元素!所以你根本聽不到音頻。

試試這個:

<audio id="audio" hidden loop> 
<source src="music.mp3" type="audio/mpeg"> 
No support for HTML5 audio! 
</audio> 

<div id="playButton" onclick="play()">PLAY</div> 
<script type="text/javascript"> 
    var audio = document.getElementById("audio"); 

    // Binding event 
    audio.oncanplay = function() { 
     alert("Can start playing video"); 
    }; 

    // Playing the audio 
    function play() { 
     audio.play(); 
    } 
</script>