How to play a notification sound on websites?

JavascriptHtmlAudioNotificationsHtml5 Audio

Javascript Problem Overview


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:

  1. What codec should I use?
  2. What's best practice to embed the audio file? (<embed> vs. <object> vs. Flash vs. <audio>)

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

Play cross browser compatible notifications

As adviced by @Tim Tisdall from this post , Check Howler.js Plugin.

Browsers like chrome disables javascript execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.

  var sound =new Howl({
                     src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
                           '../sounds/rings.aiff'],
                     autoplay: true,
                     loop: true
                    });

               sound.play();

Hope helps someone.

Solution 6 - Javascript

Use the audio.js which is a polyfill for the <audio> tag with fallback to flash.

In general, look at https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills for polyfills to the HTML 5 APIs.. (it includes more <audio> polyfills)

Solution 7 - Javascript

if you want calling event on the code The best way to do that is to create trigger because the browser will not respond if the user is not on the page

<button type="button" style="display:none" id="playSoundBtn" onclick="playSound();"></button>

now you can trigger your button when you want to play sound

$('#playSoundBtn').trigger('click');

Solution 8 - Javascript

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!

Solution 9 - Javascript

var audio = new Audio('audio_file.mp3');

function post()
{
  var tval=document.getElementById("mess").value;	
  var inhtml=document.getElementById("chat_div");
  inhtml.innerHTML=inhtml.innerHTML+"<p class='me'>Me:-"+tval+"</p>";
  inhtml.innerHTML=inhtml.innerHTML+"<p class='demo'>Demo:-Hi! how are you</p>";
  audio.play();
}

this code is from talkerscode For complete tutorial visit http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php

Solution 10 - Javascript

We can just use Audio and an object together like:

var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();

and even adding addEventListener for play and ended

Solution 11 - Javascript

I wrote a clean functional method of playing sounds:

sounds = {
	test : new Audio('/assets/sounds/test.mp3')
};

sound_volume = 0.1;

function playSound(sound) {
	sounds[sound].volume = sound_volume;
	sounds[sound].play();
}
function stopSound(sound) {
	sounds[sound].pause();
}
function setVolume(sound, volume) {
	sounds[sound].volume = volume;
	sound_volume = volume;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimo ErnstView Question on Stackoverflow
Solution 1 - JavascriptTimo ErnstView Answer on Stackoverflow
Solution 2 - JavascriptweltschmerzView Answer on Stackoverflow
Solution 3 - JavascriptCassio LandimView Answer on Stackoverflow
Solution 4 - JavascriptStarxView Answer on Stackoverflow
Solution 5 - JavascriptShaiju TView Answer on Stackoverflow
Solution 6 - JavascriptGabriele PetrioliView Answer on Stackoverflow
Solution 7 - JavascriptSfwan EssamView Answer on Stackoverflow
Solution 8 - JavascriptPhill AlexakisView Answer on Stackoverflow
Solution 9 - JavascriptramanchaView Answer on Stackoverflow
Solution 10 - JavascriptMostafaView Answer on Stackoverflow
Solution 11 - JavascriptJackView Answer on Stackoverflow