javascripthtmlaudionotificationshtml5-audio

How to play a notification sound on websites?


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

Solution

  • 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.