Raj Raj
Raj Raj

Reputation: 33

Call function after finish audio file

I have added one music audio player in my web application. I need to call a function after completing the audio. But the thing is audio length is not specified.

for example, 10 seconds audio finished then call a function, 7 seconds audio then call a function.

it means once audio complete then call function to event occur. Audio length should be not specified.

here is my audio player code

<audio controls="controls" controlsList="nodownload" onloadeddata="var audioPlayer = this; setTimeout(function() { audioPlayer.play(); }, 4000)">
<source src="'.str_replace("\'","'", $que=$row->question).'" type="audio/mp3" id="my_audio" loop="loop"/>
</audio>

This is my java script code

setTimeout(
  function() 
  {
    console.log('10 Seconds done')
  }, 10000);

Here, code in message pass after 10 seconds but I need message pass after completing audio

Upvotes: 0

Views: 1529

Answers (2)

PiggyPlex
PiggyPlex

Reputation: 703

Use the onended function.

<audio controls="controls" controlsList="nodownload" onended="console.log('ended!');">
  <source src="///file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mp3" id="my_audio">
</audio>

You could also try:

$('#my_audio').parent().play().then(() => {
  const checkAudio = () => {
    if ($('#my_audio').parent()[0].ended) {
      console.log('ended!');
    } else {
      setTimeout(checkAudio, 100);
    };
  };
});
    <audio controls="controls" controlsList="nodownload">
      <source src="///file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mp3" id="my_audio">
    </audio>

Upvotes: 0

SMAKSS
SMAKSS

Reputation: 10510

You can do this with ended event. So you should only listen for ended event on your desired element like this:

const audio = document.querySelector("audio");

audio.addEventListener('ended', (event) => {
  console.log('audio has been ended');
});
<audio controls src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3">
  Your browser does not support the <code>audio</code> element.
</audio>

Upvotes: 4

Related Questions