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.