Search code examples
javascriptplayback

How to proceed only when the audio is done playing in javascript?


I have the following javascript code

var audio = new Audio('{{ path }}');

function play() {
  audio.play();
}

statusElement = document.getElementById("audio-status")
statusElement.innerHTML = "Playing the audio"
play()
statusElement.innerHTML = "done playing the audio"

Now, when I run this code, I see that the statusElement displays "done playing the audio" while the audio is still playing.

I think that this might be because the audio.play() function runs asynchronously, however, that's not what I want.

I want to first display, "Playing the audio", and then wait for the audio to play, and after that display "done playing the audio". How should I go about doing this?


Solution

  • There is an event ended that can help in this case as MDN mentions

    The ended event is fired when playback or streaming has stopped because the end of the media was reached or because no further data is available.

    So you could try something like this

    const audio = document.querySelector('audio');
    
    audio.addEventListener('ended', () => {
      statusElement.innerHTML = "done playing the audio"
    });
    

    for more info check the docs here