Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTconst audio = new Audio("sound.mp3");
audio.play();
Once it is play, you can also pause the sound by calling the pause()
method:
JAVASCRIPTconst audio = new Audio("sound.mp3");
audio.play();
audio.pause();
Additionally, you can restart the sound from the start by calling the load()
method:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Create an RSS Reader in Node
- Getting Started with Electron
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up Stylus CSS Preprocessor