6
votes

With the new Html5 audio tag, the onplay event only seems to fire the first time the audio is played. In this example, when clicking "Play", the audio kicks off with an alert popup showing "Playing." When the audio has finished and "Play" is clicked again, the audio kicks off again but no alert is fired. Am I missing something here? Do I have to reset the audio somehow?

<a href="#" onclick="$('#audio')[0].play();">Play</a>

<audio preload="none" id="audio" onplay="alert('playing');"><source type="audio/wav" src="..."></source></audio>

I have also tried binding to the play event with jQuery, but I get the same results.

<a href="#" onclick="$('#audio')[0].play(); return false;">Play</a>

<audio preload="none" id="audio"><source type="audio/wav" src="..."></source></audio>

<script type="text/javascript">

    $(document).ready(function () {

        $('#audio')[0].bind('play', function () {

            alert("Playing");

        });

    });    

</script>
1

1 Answers

7
votes

onplay is run when the media is ready to start running,

The element is no longer paused. Fired after the play() method has returned, or when the autoplay attribute has caused playback to begin.

taken from the spec

You could try

<input type="button" value="Play" id="play_pause" onclick="audio.play()">

and then

var play_pause = document.getElementById('play_pause');
video.onpause = function(e) {
  play_pause.value = 'Play';
  play_pause.onclick = function(e) { video.play(); }
}
video.onplay = function(e) {
  play_pause.value = 'Pause';
  play_pause.onclick = function(e) { video.pause(); }
}

source