How to Play a Sound using Audio in JavaScript
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 Solid
- Getting Started with Svelte
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js