How to Play a Sound using Audio in JavaScript

Updated onbyAlan Morel
How to Play a Sound using Audio in JavaScript

JavaScript allows us full control over the user experience thanks its built-in web APIs.

One of the most powerful ones is the ability to play an audio file to the user.

In this post, we'll learn how to play a sound using the Audio web API in JavaScript.

How to play a sound in JavaScript

To play a sound in JavaScript, we can leverage the Audio web API to create a new HTMLAudioElement instance.

Let's see how to do it:

JAVASCRIPT
const audio = new Audio("sound.mp3");

The Audio constructor accepts a string argument that represents the path to the audio file.

The browser will then download the audio file and prepare it for playback.

To play this sound, we can call the play() method on the audio instance:

JAVASCRIPT
const audio = new Audio("sound.mp3"); audio.play();

Once it is play, you can also pause the sound by calling the pause() method:

JAVASCRIPT
const audio = new Audio("sound.mp3"); audio.play(); audio.pause();

Additionally, you can restart the sound from the start by calling the load() method:

JAVASCRIPT
const audio = new Audio("sound.mp3"); audio.play(); audio.pause(); audio.load();

You can even attach event listeners to the audio instance to listen for events such as play, pause, ended, and error.

For example, to listen for the ended event, you can do the following:

JAVASCRIPT
const audio = new Audio("sound.mp3"); audio.addEventListener("ended", () => { console.log("The sound has ended"); });

The Audio web API is powerful and allows you to perform many actions with a sound file and to listen to those events.

Conclusion

In this post, we learned how to play a sound in JavaScript using the Audio web API.

We saw how to create a new HTMLAudioElement instance and how to play, pause, and restart the sound.

We also saw how to listen for events such as play, pause, ended, and error.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.