3

I am working on an HTML5 audio tag and I want to trigger an event when the song is finished. Is this possible with jQuery?

My jQuery code is:

      $(document).ready(function(){

var music = new Audio("sample.mp3");
$('#play').click(function(){
    music.play();
});

$('#pause').click(function(){
 music.pause();
});

         });

My HTML5 is:

<input type="button" value="Play" id="play" />
<input type="button" value="Pause" id=pause" />
Graham
  • 3,153
  • 3
  • 16
  • 31
danny
  • 407
  • 1
  • 5
  • 10
  • Related: [Need to trigger an event on a video ending](http://stackoverflow.com/questions/7588921/7588975#7588975) – Pekka Oct 04 '11 at 17:58

3 Answers3

14

Use HTML 5 onended event handler

<audio src="sample.mp3" onended="yourFunction()"></audio>

For jQuery bind ended event handler

 $(music).bind("ended", function(){ ... });
Emmanuel N
  • 7,350
  • 2
  • 26
  • 36
  • thanks for reply actually i want to trigger it through jquery how its possible with jquery? – danny Oct 04 '11 at 18:21
  • For jQuery bind ended event handler. Something like, `$(music).bind("ended", function(){ ... });` – Emmanuel N Oct 04 '11 at 18:27
  • @danny what browser are you using? – Emmanuel N Oct 04 '11 at 18:38
  • i just tested $(music).bind("ended", function(){ ... }); it works fine i am using chrome. I have replaced the code music.addEventListener("ended", function() { }); to $(music).bind("ended", function(){ alert('fired');}); its perfect thanks. – danny Oct 04 '11 at 19:01
  • Emmanule if you edit your reply and add audio status function etc file is paused or stopped etc it would help lots of people. – danny Oct 04 '11 at 19:14
3
.bind("ended", function(){ });

Or

 music.addEventListener("ended", function() { });
Dave Hogan
  • 3,201
  • 6
  • 29
  • 54
  • thanks for reply but its not working. i dont know whats wrong i have used music.bind("ended, function(){}); – danny Oct 04 '11 at 18:22
  • music.addEventListener("ended", function() { }); is working perfectly – danny Oct 04 '11 at 18:39
0
<audio class="ah-audio-player" preload="auto">
  <source type="audio/mpeg" src="sound.mp3">
</audio>

-

var audio_player = $('.ah-audio-player');
audio_player.on('ended', function () {
    alert('end');
});
Abdo-Host
  • 2,470
  • 34
  • 33