Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect an audio has finished playing in a web page?

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.

like image 268
limc Avatar asked Jan 06 '11 21:01

limc


People also ask

How do you check if an audio is done playing in JavaScript?

To check if audio is playing with JavaScript, we can use the paused property of the audio element. const isPlaying = (audElem) => { return ! audElem. paused; };

What tag plays an audio on the web page?

The HTML <audio> element is used to play an audio file on a web page.

Which HTML element is used for playing audio files?

The <audio> HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one.


2 Answers

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.

like image 51
Adilson de Almeida Jr Avatar answered Sep 20 '22 04:09

Adilson de Almeida Jr


You can also add a jQuery event listener like so:

$("audio").on("ended", function() {
    console.log("All Done!");
});
like image 30
Justin Eldracher Avatar answered Sep 20 '22 04:09

Justin Eldracher