How to Play a Notification Sound on Websites

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

  • <audio> (Modern browsers)
  • <embed> (Fallback)

Codes used

  • MP3 for Chrome, Safari and Internet Explorer.
  • OGG for Firefox and Opera.

How to play notification sound on website since google autoplay policy change

The problem is that autoplay sound will be blocked under some circumstance according to the autoplay policy of Chrome.

Autoplay with sound is allowed if:

  • User has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound.
  • The user has added the site to their home screen on mobile or installed the PWA on desktop.
  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.

See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio for more details.

How to play a sound notification with Chrome for Android with Javascript?

At least this trick allows to know in advance if media playback requires user gesture:

function mediaPlaybackRequiresUserGesture() { 
var audio = document.createElement('audio');
audio.play();
return audio.paused;
}

Found here.

Playing Notification Sound with JavaScript

Cache the last response and compare it with the new version to determine whether or not to play the audio file.

var lastResponse = ''

setInterval(function() {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function(response) {
$(".msg_area").html(response)
if (lastResponse && response !== lastResponse) {
var audio = new Audio('audio_file.mp3')
audio.play()
}
lastResponse = response
}
});
}, 2000);

Edit: If you want audio to play the first time a response comes in, remove lastResponse && from the code above.

Playing a Sound Notification when Specific Text on Page Appears

I simply changed the RegEx code to var watchRegx = /2 credits/; A simple enough solution. Thanks for all the feedback



Related Topics



Leave a reply



Submit