How to play a sound with JavaScript

Today, we’re going to look at how to use vanilla JS to play a sound in the browser. Let’s dig in!
Quick aside: autoplaying unwanted background sounds on a webpage can very intrusive and create a terrible user experience. Use this with care!
The new Audio() constructor The new Audio() constructor lets you create a new HTMLAudioElement. Pass in the URL of the audio file as an argument.
let beat = new Audio(‘/path/to/my/beat.


This content originally appeared on Go Make Things and was authored by Go Make Things

Today, we’re going to look at how to use vanilla JS to play a sound in the browser. Let’s dig in!

Quick aside: autoplaying unwanted background sounds on a webpage can very intrusive and create a terrible user experience. Use this with care!

The new Audio() constructor

The new Audio() constructor lets you create a new HTMLAudioElement. Pass in the URL of the audio file as an argument.

let beat = new Audio('/path/to/my/beat.mp3');

After you create it, you can use all of the same methods available on an <audio> element: HTMLAudioElement.play(), HTMLAudioElement.pause(), and HTMLAudioElement.load() most notably.

// Play the beat
beat.play();

// Pause/stop the beat
beat.pause();

// Reload the beat (back to the start)
beat.load();

Example: a timer app

Let’s say we have a simple timer app that counts down to 0.

It has a count variable that starts at 5. We use the setInterval() method to run a callback function every 1000 milliseconds (or every one second).

Inside that callback, we decrease the count by 1 with the decrement operator (--). If the count is greater than 0, we show it. Otherwise, we use clearInterval() to stop the timer, and show an alarm clock emoji (⏰) instead.

<div id="app" aria-live="polite">5</div>
// Get the #app element
let app = document.querySelector('#app');

// Track the count
let count = 5;

// Run a callback function once every second
let timer = setInterval(function () {

	// Reduce count by 1
	count--;

	// Update the UI
	if (count > 0) {
		app.textContent = count;
	} else {
		app.textContent = '⏰';
		clearInterval(timer);
	}

}, 1000);

Here’s a demo.

Now, what if you wanted to play a chime when the alarm ends?

Adding a chime to the alarm

For this project, I downloaded the “ding-dong sound effect” from Free Sounds Library, and saved it as ding.mp3 in my project directory.

Next, I added a playSound() function.

In it, I create a new Audio() object from the ding.mp3 file. Then, I use the ding.play() method to make it play.

/**
 * Play the chime sound
 */
function playSound () {
	let ding = new Audio('ding.mp3');
	ding.play();
}

Back in the callback function for my setInterval() method, I run the playSound() method when the timer reaches 0.

// Run a callback function once every second
let timer = setInterval(function () {

	// Reduce count by 1
	count--;

	// Update the UI
	if (count > 0) {
		app.textContent = count;
	} else {
		app.textContent = '⏰';
		clearInterval(timer);
		playSound();
	}

}, 1000);

Now, whenever the timer ends, a gentle “ding dong” sound is played.

Play around with the source code on GitHub.


This content originally appeared on Go Make Things and was authored by Go Make Things


Print Share Comment Cite Upload Translate Updates
APA

Go Make Things | Sciencx (2021-07-19T14:30:00+00:00) How to play a sound with JavaScript. Retrieved from https://www.scien.cx/2021/07/19/how-to-play-a-sound-with-javascript/

MLA
" » How to play a sound with JavaScript." Go Make Things | Sciencx - Monday July 19, 2021, https://www.scien.cx/2021/07/19/how-to-play-a-sound-with-javascript/
HARVARD
Go Make Things | Sciencx Monday July 19, 2021 » How to play a sound with JavaScript., viewed ,<https://www.scien.cx/2021/07/19/how-to-play-a-sound-with-javascript/>
VANCOUVER
Go Make Things | Sciencx - » How to play a sound with JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/19/how-to-play-a-sound-with-javascript/
CHICAGO
" » How to play a sound with JavaScript." Go Make Things | Sciencx - Accessed . https://www.scien.cx/2021/07/19/how-to-play-a-sound-with-javascript/
IEEE
" » How to play a sound with JavaScript." Go Make Things | Sciencx [Online]. Available: https://www.scien.cx/2021/07/19/how-to-play-a-sound-with-javascript/. [Accessed: ]
rf:citation
» How to play a sound with JavaScript | Go Make Things | Sciencx | https://www.scien.cx/2021/07/19/how-to-play-a-sound-with-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.