How to play a notification sound on websites?

166,632

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!

Share:
166,632
Timo Ernst
Author by

Timo Ernst

Coding Architect at Audi Business Innovation JavaScript Enthusiast YouTube Coding Tutor: http://www.timoernst.tv

Updated on February 03, 2022

Comments

  • Timo Ernst
    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:

    1. What codec should I use?
    2. What's best practice to embed the audio file? (<embed> vs. <object> vs. Flash vs. <audio>)
  • Stefan
    Stefan about 12 years
    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.
  • Timo Ernst
    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
    Timo Ernst about 12 years
    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..
  • Starx
    Starx about 12 years
    @valmar: visiblity: hidden; is your answer
  • Jagdeep Singh
    Jagdeep Singh about 11 years
    Thank you so much for the solution @valmar
  • Timo Ernst
    Timo Ernst over 10 years
    @DavidLarsson Because there are some browsers that cannot read certain codecs.
  • joppiesaus
    joppiesaus almost 10 years
    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.
  • Md. Arafat Al Mahmud
    Md. Arafat Al Mahmud over 9 years
    I failed to make it work with my Internet Explorer version 8.
  • Shaiju T
    Shaiju T almost 8 years
    This doesn't plays notification sounds if browser is inactive or minimized by the user. Check this post for solution. Hope helps someone.
  • poshest
    poshest almost 7 years
    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?
  • Shaiju T
    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
    poshest almost 7 years
    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, so I thought you knew something special about it.
  • Christophe Roussy
    Christophe Roussy almost 6 years
    And maybe also check if Audio is defined before doing this.
  • Polaris
    Polaris over 5 years
    This is a great answer, so simple and works perfectly.
  • jack blank
    jack blank almost 5 years
    Doesn't work anymore I get Uncaught (in promise) DOMException
  • Dennis Hackethal
    Dennis Hackethal almost 5 years
    Just tried it on the latest Chrome (version 74.0.3729.169) and it works for me.
  • Muhammad Omer Aslam
    Muhammad Omer Aslam over 4 years
    it 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
    Maxie Berkmann about 4 years
    This should be the accepted answers as it's simpler and not doing unneeded expensive DOM manipulation.
  • mozgras
    mozgras over 2 years
    @ShaijuT Thank you!
  • Joseph Ali
    Joseph Ali about 2 years
    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
    Joseph Ali about 2 years
    @jack blank i got same problem any solution i tried many, but still
  • Joseph Ali
    Joseph Ali about 2 years
    btw how to import to js file ?!
  • Cassio Landim
    Cassio Landim about 2 years
    Read "Usage" section of github.com/IonDen/ion.sound documentation. @joseph-ali
  • Timo Ernst
    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
    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!