40

I am having a problem detecting when an tag is finished playing an mp3. When I do something like this:

     myAudio.addEventListener("ended", function() 
     {
          alert("ended");
     });

It only occurs the first time the audio is played. When I play the audio again, nothing happens. The same thing happens when I use the onended=doThis(); method. I've heard maybe there is a way to do it in jQuery, but I haven't been able to get it to work. I've also heard there might be a way to fix it by changing the audio div id every time the mp3 is played, but this doesn't work for me because I need the id to stay the same.

Did anyone get any ideas?

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
evenodd
  • 2,026
  • 4
  • 26
  • 38

1 Answers1

61

The ended event is created based on .currentTime attribute. http://w3c.github.io/html/semantics-embedded-content.html#eventdef-media-ended

So, all you have to do is set the .currentTime to zero again.

myAudio.addEventListener("ended", function(){
     myAudio.currentTime = 0;
     console.log("ended");
});
kamoroso94
  • 1,713
  • 1
  • 16
  • 19
Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43
  • 2
    That did it! But I also had to pause it before that because otherwise it would just be an endless loop – evenodd Jun 19 '12 at 15:51
  • I tried this but for me it didn't work. though i found re-adding the event listener before each play did the trick for me. I'm using the Tizen Web so api so not sure if that's what's causing it to be different for me or not. but thought it worth mentioning. – Kit Ramos Sep 09 '18 at 15:55
  • one other thing i found out when using Tizen. using this method will not guarantee that the effects of the function will happen after the media has ended, they will happen just not always after the media has actually ended. it's better to put the onended into the html tag as that has that was the only way I could get it to work as expected. – Kit Ramos Sep 09 '18 at 16:16