22

In my project, I need to embed audio (ex: mp3, etc) into a web page. When user visits the page, the audio will begin playing. When the audio ends, the questionnaire (form fields) will appear for the user to answer.

Is there is way to check if the audio has finished playing using jquery, so that the questionnaire can appear after the user has listened to the entire audio?

I know one way to check is to determine the audio length, then I can set a timer to display the questionnaire, but I'm hoping jquery has some sort of event handler that allows me to accomplish this.

I see that jquery has many audio plugins, and I can't be sure which will do what I want here: http://plugins.jquery.com/plugin-tags/audio

Any ideas are greatly appreciated.

Thanks.

limc
  • 39,366
  • 20
  • 100
  • 145

3 Answers3

32

If you are using the html5 audio tag, there is the "onended" event handler. I don´t know if the browsers support it yet.

Something like:

<audio src="xpto.mp3" onended="DoSomething();"></audio>

In the last case you can use a swf that can play the sound, and alert your javascript when it reaches the end.

Adilson de Almeida Jr
  • 2,761
  • 21
  • 37
  • Unfortunately, I work in a corporation where IE 7 is currently the "preferred" browser, and it seems like only IE 9 onwards will have HTML5. – limc Jan 06 '11 at 21:50
  • So you should use a flash player. Try the XSPF – Adilson de Almeida Jr Jan 06 '11 at 22:41
  • 1
    I can't use flash in this project. While this web app will run using IE, I will need to port this web app to iPad devices in the future, and flash is not supported in iPad. – limc Jan 07 '11 at 03:46
  • Using jquery I got it working using bind $("player").bind("ended", function(){window.location = '/nextpage';}); – michela Oct 09 '11 at 07:57
  • I find if your using the Tizen Web api this method works much better then using addEventListener as if you use that the code in the function call can still affect the audio as it's playing. but this way it actually does wait for the media to finish playing first. – Kit Ramos Sep 09 '18 at 16:11
4

You can also add a jQuery event listener like so:

$("audio").on("ended", function() {
    console.log("All Done!");
});
2

Using JavaScript event listener.

var myAudio = document.getElementById("myAudioId");

myAudio.addEventListener("ended", function() {
    alert("The audio has ended.");
};
Rodgath
  • 535
  • 5
  • 9