admin管理员组文章数量:1328029
I'm trying to determine when an HTML5 audio element is ready to start playing so I can inform the user. I'm using the following code:
<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>
However, the alert never appears, even after pressing the playButton. Im using the lates Chrome (Chrome 40)
I'm trying to determine when an HTML5 audio element is ready to start playing so I can inform the user. I'm using the following code:
<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>
However, the alert never appears, even after pressing the playButton. Im using the lates Chrome (Chrome 40)
Share Improve this question asked Feb 7, 2015 at 7:10 Hussain KhalilHussain Khalil 1,6602 gold badges17 silver badges24 bronze badges 1- hope it will help you :) stackoverflow./questions/10790091/… – user4523269 Commented Feb 7, 2015 at 7:25
2 Answers
Reset to default 4You are getting element before JavaScript even finds it! So you don't get audio at all.
Try this one:
<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>
Adding on to what Shreejibawa posted, about your script needing to be executed after the DOM is loaded, take a look at the docs for HTML5 audio and javascript events.
https://developer.mozilla/en-US/docs/Web/Events/canplay
本文标签: javascriptcanplay HTML5 Audio event not firingStack Overflow
版权声明:本文标题:javascript - `canplay` HTML5 Audio event not firing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742239346a2438667.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论