How to play a notification sound on websites?

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.

Leave a Comment