Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`canplay` HTML5 Audio event not firing

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)

like image 448
Hussain Khalil Avatar asked Oct 19 '25 04:10

Hussain Khalil


1 Answers

You 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>
like image 92
Shreejibawa Avatar answered Oct 20 '25 17:10

Shreejibawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!