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:
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:
const audio = new Audio("sound.mp3");
audio.play();
Once it is play, you can also pause the sound by calling the pause()
method:
const audio = new Audio("sound.mp3");
audio.play();
audio.pause();
Additionally, you can restart the sound from the start by calling the load()
method:
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:
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!