Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html5 lazy 'onplay' event handler for Audio tag?

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>
like image 363
Levitikon Avatar asked Oct 05 '11 16:10

Levitikon


People also ask

How to embedded audio file in HTML?

To embed audio in HTML, we use the <audio> tag. Before HTML5, audio cannot be added to web pages in the Internet Explorer era. To play audio, we used web plugins like Flash.

What attributes control audio tag?

The HTML <audio> controls attribute is used to specify the control to play audio. It is the Boolean value.

How to embed audio on website?

An easy way to embed audio on a website is by using a sound hosting site, such as SoundCloud or Mixcloud. All you need to do is upload the file and receive an HTML embed code. Then copy and paste the embed code into the web page's code or WYSIWYG site editor. This works for most CMS platforms and website builders.


1 Answers

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

like image 133
Mansuro Avatar answered Oct 13 '22 02:10

Mansuro