How to play a notification sound on websites?
Solution 1
2021 solution
function playSound(url) {
const audio = new Audio(url);
audio.play();
}
<button onclick="playSound('https://your-file.mp3');">Play</button>
Browser support
Edge 12+, Firefox 20+, Internet Explorer 9+, Opera 15+, Safari 4+, Chrome
Codecs Support
Just use MP3
Old solution
(for legacy browsers)
function playSound(filename){
var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename +'.mp3">';
document.getElementById("sound").innerHTML='<audio autoplay="autoplay">' + mp3Source + oggSource + embedSource + '</audio>';
}
<button onclick="playSound('bing');">Play</button>
<div id="sound"></div>
Browser support
Codes used
- MP3 for Chrome, Safari and Internet Explorer.
- OGG for Firefox and Opera.
Solution 2
As of 2016, the following will suffice (you don't even need to embed):
let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();
See more here.
Solution 3
One more plugin, to play notification sounds on websites: Ion.Sound
Advantages:
- JavaScript-plugin for playing sounds based on Web Audio API with fallback to HTML5 Audio.
- Plugin is working on most popular desktop and mobile browsers and can be used everywhere, from common web sites to browser games.
- Audio-sprites support included.
- No dependecies (jQuery not required).
- 25 free sounds included.
Set up plugin:
// set up config
ion.sound({
sounds: [
{
name: "my_cool_sound"
},
{
name: "notify_sound",
volume: 0.2
},
{
name: "alert_sound",
volume: 0.3,
preload: false
}
],
volume: 0.5,
path: "sounds/",
preload: true
});
// And play sound!
ion.sound.play("my_cool_sound");
Solution 4
How about the yahoo's media player Just embed yahoo's library
<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script>
And use it like
<a id="beep" href="song.mp3">Play Song</a>
To autostart
$(function() { $("#beep").click(); });
Solution 5
if you want to automate the process via JS
:
Include somewhere in the html
:
<button onclick="playSound();" id="soundBtn">Play</button>
and hide it via js
:
<script type="text/javascript">
document.getElementById('soundBtn').style.visibility='hidden';
function performSound(){
var soundButton = document.getElementById("soundBtn");
soundButton.click();
}
function playSound() {
const audio = new Audio("alarm.mp3");
audio.play();
}
</script>
if you want to play the sound just call performSound()
somewhere!
Timo Ernst
Coding Architect at Audi Business Innovation JavaScript Enthusiast YouTube Coding Tutor: http://www.timoernst.tv
Updated on February 03, 2022Comments
-
Timo Ernst over 2 years
When a certain event occurs, I want my website to play a short notification sound to the user.
The sound should not auto-start (instantly) when the website is opened. Instead, it should be played on demand via JavaScript (when that certain event occurs).
It is important that this also works on older browsers (IE6 and such).
So, basically there are two questions:
- What codec should I use?
- What's best practice to embed the audio file? (
<embed>
vs.<object>
vs. Flash vs.<audio>
)
-
Stefan about 12 yearsNice answer. In this case though the sound does play instantly when the page is opened - but I assume you show how, just for demonstration purposes.
-
Timo Ernst about 12 years@Stefan That's correct but may be confusing. I'll remove that from my answer. Thanks for the hint.
-
Timo Ernst about 12 yearsAlso a nice solution but would it be possible to hide that link? I think if you set
display: none
for it, it won't play the sound anymore. Also, the Yahoo media library shows a small "play" icon left of the link.. -
Starx about 12 years@valmar:
visiblity: hidden;
is your answer -
Jagdeep Singh about 11 yearsThank you so much for the solution @valmar
-
Timo Ernst over 10 years@DavidLarsson Because there are some browsers that cannot read certain codecs.
-
joppiesaus almost 10 yearsIf you want to make the sound repeat infinitely add an attribute in
audio
like this:loop="true"
and setloop
inembed
totrue
. -
Md. Arafat Al Mahmud over 9 yearsI failed to make it work with my Internet Explorer version 8.
-
Shaiju T almost 8 yearsThis doesn't plays notification sounds if browser is inactive or minimized by the user. Check this post for solution. Hope helps someone.
-
poshest almost 7 yearsHow does "This plays notification sounds even if browser is inactive or minimized"? The sound might play if called when the page is asleep, but how does the code which calls
sound.play()
run in the first place? Does howler put all your setTimeouts in a wrapper? -
Shaiju T almost 7 years@poshest , I don't know how it plays , may be checking the source code or contacting the author of plugin may help you.
-
poshest almost 7 yearsOK, thanks. It's just that you mentioned this feature and linked that other Stackoverflow answer, but it's not mentioned as a feature in the Howler documentation, so I thought you knew something special about it.
-
Christophe Roussy almost 6 yearsAnd maybe also check if Audio is defined before doing this.
-
Polaris over 5 yearsThis is a great answer, so simple and works perfectly.
-
jack blank almost 5 yearsDoesn't work anymore I get
Uncaught (in promise) DOMException
-
Dennis Hackethal almost 5 yearsJust tried it on the latest Chrome (version 74.0.3729.169) and it works for me.
-
Muhammad Omer Aslam over 4 yearsit works correctly on chrome, FF and opera and is alot better approach than the accepted answer as that answer keeps appending the audio tag to your body tag as the notifications script will most probably be called in intervals
-
Maxie Berkmann about 4 yearsThis should be the accepted answers as it's simpler and not doing unneeded expensive DOM manipulation.
-
mozgras over 2 years@ShaijuT Thank you!
-
Joseph Ali about 2 yearsit worked in firefox, but in chrome I get this error in the console :
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
-
Joseph Ali about 2 years@jack blank i got same problem any solution i tried many, but still
-
Joseph Ali about 2 yearsbtw how to import to js file ?!
-
Cassio Landim about 2 yearsRead "Usage" section of github.com/IonDen/ion.sound documentation. @joseph-ali
-
Timo Ernst about 2 years@JosephAli You need to make sure that the code is run as a result of a user interaction (e.g. click event from a button). Otherwise it won't work because browser manufacturers want to prevent sound/music to suddenly play back without approval of the user.
-
Joseph Ali about 2 years@Timo Ernst thanks, but I have this requirement: notifying admin whenever a new order is submitted by online shop customers!