Categories
JavaScript Answers

How to Tell When an HTML5 Audio Element has Finished Playing with JavaScript?

Spread the love

To tell when an HTML5 audio element has finished playing with JavaScript, we can listen to the ended event emitted by the audio element.

For instance, we can write:

<audio id="music" controls src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"></audio>

to add the audio element.

Then we can listen to the ended event that’s emitted by the audio element when the audio finishes playing by writing the following JavaScript code:

document.querySelector("#music").addEventListener("ended", () => {
  console.log('ended')
});

We select the audio element with:

document.querySelector("#music")

Then we call addEventListener with 'ended' to listen to the ended event.

Then 2nd argument is the callback that runs when the audio finishes playing.

Now when the clip finishes playing, we should see 'ended' logged.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.