139

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>)
Oskar Eriksson
  • 2,591
  • 18
  • 32
Timo Ernst
  • 15,243
  • 23
  • 104
  • 165
  • You can try https://github.com/VJAI/musquito – VJAI Aug 01 '18 at 17:39
  • 1
    @John The question asked for a manual solution. Besides that, browsers do now allow automatic auto-play, so there is nothing you can do as a developer to support this anyway. – Timo Ernst Aug 26 '22 at 12:33

11 Answers11

172

2023 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.
Timo Ernst
  • 15,243
  • 23
  • 104
  • 165
  • Nice 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. – Stefan Apr 11 '12 at 15:47
  • @Stefan That's correct but may be confusing. I'll remove that from my answer. Thanks for the hint. – Timo Ernst Apr 11 '12 at 16:09
  • @DavidLarsson Because there are some browsers that cannot read certain codecs. – Timo Ernst Oct 22 '13 at 15:33
  • If you want to make the sound repeat infinitely add an attribute in `audio` like this: `loop="true"` and set `loop` in `embed` to `true`. – joppiesaus May 19 '14 at 13:58
  • 2
    I failed to make it work with my Internet Explorer version 8. – Md. Arafat Al Mahmud Sep 01 '14 at 11:57
  • This doesn't plays notification sounds if **browser is inactive or minimized** by the user. Check [this](http://stackoverflow.com/a/38571639/2218697) post for **solution**. Hope helps someone. – Shaiju T Jul 25 '16 at 15:22
  • 1
    @ShaijuT Thank you! – mozgras Sep 22 '21 at 18:51
  • 3
    it 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 Apr 03 '22 at 11:35
  • @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. – Timo Ernst Apr 29 '22 at 09:06
  • @Timo Ernst thanks, but I have this requirement: notifying admin whenever a new order is submitted by online shop customers! – Joseph Ali Apr 29 '22 at 17:41
  • What about the WAV format? It works well on Chrome with this solution but is it a standard? – Meloman Jul 04 '22 at 07:13
  • @Meloman I‘d say wav files would be too large because uncompressed. – Timo Ernst Jul 05 '22 at 08:53
89

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.

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
18

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");
IonDen
  • 773
  • 5
  • 15
Cassio Landim
  • 1,929
  • 23
  • 25
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(); });
Starx
  • 77,474
  • 47
  • 185
  • 261
  • Also 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.. – Timo Ernst Apr 11 '12 at 16:14
  • @valmar: `visiblity: hidden;` is your answer – Starx Apr 11 '12 at 16:22
4

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.

Community
  • 1
  • 1
Shaiju T
  • 6,201
  • 20
  • 104
  • 196
  • How 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? – poshest Aug 07 '17 at 09:43
  • @poshest , I don't know how it plays , may be checking the source code or contacting the author of plugin may help you. – Shaiju T Aug 07 '17 at 10:08
  • 1
    OK, 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](https://github.com/goldfire/howler.js/), so I thought you knew something special about it. – poshest Aug 07 '17 at 12:01
4

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!

Phill Alexakis
  • 1,449
  • 1
  • 12
  • 31
3

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');
2

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)

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1
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

ramancha
  • 31
  • 1
1

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;
}
Jack
  • 3,271
  • 11
  • 48
  • 57
0

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

Mostafa
  • 815
  • 1
  • 13
  • 23