- How to play a sound with JavaScript
- The new Audio() constructor
- Example: a timer app
- Adding a chime to the alarm
- 10 Effective Ways to Play Sound on Your Webpage with Javascript
- Introduction
- Using the autoplay attribute in the or element
- Play Audio in JavaScript After Page Load or Delay Time
- Using the HTML DOM Audio play() method
- Playing sound on user interaction
- Using the HTML5 tag to load and play sound files
- Autoplay with sound
- Using the Audio() Web API to configure and play audio from a specified URL
- Advanced techniques for playing sound with JavaScript
- Best practices and common issues
- Other quick examples for playing sound when page opens using Javascript
- Conclusion
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.mp3');
After you create it, you can use all of the same methods available on an 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">5div>
// 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);
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.
Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.
Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.
10 Effective Ways to Play Sound on Your Webpage with Javascript
Learn how to play sound on your webpage with Javascript. Use autoplay, HTML DOM Audio play(), user interaction and advanced techniques. Follow best practices and avoid common issues. Try it now!
- Introduction
- Using the autoplay attribute in the or element
- Play Audio in JavaScript After Page Load or Delay Time
- Using the HTML DOM Audio play() method
- Playing sound on user interaction
- Using the HTML5 tag to load and play sound files
- Autoplay with sound
- Using the Audio() Web API to configure and play audio from a specified URL
- Advanced techniques for playing sound with JavaScript
- Best practices and common issues
- Other quick examples for playing sound when page opens using Javascript
- Conclusion
- How to play audio when page is loaded in JavaScript?
- How to play audio automatically in JavaScript?
- How can you play a background sound when the page loads?
- How to play a sound on click js?
As web development continues to evolve, it’s becoming increasingly important to provide engaging and interactive experiences for website users. One way to achieve this is by adding sound effects to webpages. Sound can be used to provide feedback, enhance user experience, and add an extra layer of interest to a website. In this article, we will explore 10 effective ways to play sound on your webpage using JavaScript.
Introduction
Playing sound on a webpage can significantly enhance the user experience. For instance, it can be used to provide feedback on user actions or to create an immersive experience for website visitors. JavaScript is a popular programming language used to add interactivity to webpages. It can also be used to play sound on webpages, making it a powerful tool for web developers. In this article, we will explore various ways to play sound on a webpage using JavaScript.
Using the autoplay attribute in the or element
The autoplay attribute is used to automatically start playing media files when a webpage loads. It can be used to play sound on a webpage when it loads. However, this approach may not work on all browsers, and it can also be a nuisance to users. The following code snippet shows how to use the autoplay attribute to play sound on a webpage.
audio autoplay> source src="audio.mp3" type="audio/mpeg"> audio>
Play Audio in JavaScript After Page Load or Delay Time
Using the HTML DOM Audio play() method
Another way to play sound on a webpage using JavaScript is by using the HTML DOM Audio play() method . This method can be used to play sound when a user interacts with a webpage. The following code snippet shows how to use the HTML DOM Audio play() method.
var audio = new Audio('audio.mp3'); audio.play();
Playing sound on user interaction
Playing sound on user interaction can also be achieved by detecting events and playing or pausing audio accordingly. For instance, sound can be played when a user clicks a button or interacts with an element on a webpage. The following code snippet shows how to play sound on click.
document.getElementById("myButton").addEventListener("click", function() var audio = new Audio('audio.mp3'); audio.play(); >);
Additionally, the cookies policy button can be used to force users to interact with a website and trigger sound playing. However, care should be taken to avoid annoying users with excessive sound.
Using the HTML5 tag to load and play sound files
The HTML5 tag can also be used to play sound on a webpage. This tag can be used to load and play sound files, and it provides various attributes for customization. The following code snippet shows how to use the HTML5 tag.
audio controls> source src="audio.mp3" type="audio/mpeg"> audio>
Autoplay with sound
Autoplay with sound is a technique that automatically starts playing sound on a webpage. This technique can be used to create immersive experiences for users. However, it can also be intrusive and annoying to users. Care should be taken when using this technique, and it should only be used on specific occasions when it is necessary. The following code snippet shows how to use autoplay with sound.
audio autoplay> source src="audio.mp3" type="audio/mpeg"> audio>
Using the Audio() Web API to configure and play audio from a specified URL
The Audio() Web API is a powerful tool for playing sound on a webpage. It provides various methods and properties for configuring and playing audio from a specified URL. The following code snippet shows how to use the Audio() Web API.
var audio = new Audio('audio.mp3'); audio.play();
Advanced techniques for playing sound with JavaScript
Advanced techniques for playing sound with JavaScript include the Web Audio API and AudioContext. These techniques provide advanced features for creating and manipulating sound on a webpage. The following code snippet shows how to use the Web Audio API.
var audioContext = new AudioContext(); var source = audioContext.createBufferSource(); var request = new XMLHttpRequest(); request.open('GET', 'audio.mp3', true); request.responseType = 'arraybuffer'; request.onload = function() var audioData = request.response; audioContext.decodeAudioData(audioData, function(buffer) source.buffer = buffer; source.connect(audioContext.destination); source.start(0); >); >; request.send();
Best practices and common issues
When playing sound on a webpage using JavaScript, it’s important to follow best practices to avoid common issues. Best practices include providing a way for users to disable sound, optimizing sound files for faster loading, and avoiding excessive sound. Common issues include compatibility issues with different browsers, large file sizes, and sound not playing on mobile devices.
Other quick examples for playing sound when page opens using Javascript
In Javascript as proof, play sound javascript code example
var audio = new Audio("folder_name/audio_file.mp3"); audio.play();
In Html , in particular, play sound in javascript code example
In Javascript , in particular, play sound javascript code sample
var audio = new Audio('audio_file.mp3'); audio.play();
In Javascript case in point, how to play sound on load js code sample
var sample = document.getElementById("foobar"); sample.play();
In Javascript , for instance, how to play sound on load js code example
In Javascript case in point, how to play sound on load js
Conclusion
Playing sound on a webpage using JavaScript can significantly enhance the user experience. In this article, we have explored 10 effective ways to play sound on a webpage using JavaScript, including using the autoplay attribute, using the HTML DOM Audio play() method, playing sound on user interaction, using the HTML5 tag, autoplay with sound, using the Audio() Web API, advanced techniques, and best practices. By following these techniques and best practices, web developers can create engaging and interactive experiences for their users.