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.
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.
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.
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.
Related Topics
Capture Browser Console Logs with Capybara
Template Literal Inside of the Regex
Creating a "Sticky" Fixed-Position Item That Works on iOS Safari
Dt: Link Binding Is Lost After Re-Rendering the Table
How to Execute Array of Promises in Sequential Order
Ios: Authentication Using Xmlhttprequest - Handling 401 Response
Why Does the Promise Constructor Need an Executor
Converting JSON Format to CSV to Upload Data Table in R to Produce D3 Bubble Chart
How to Remove a Character from a String Using JavaScript
Using Enter Key with Action Button in R Shiny
What Is the "Best" Way to Get and Set a Single Cookie Value Using JavaScript
Shiny App:Disable Downloadbutton
How to Control the Back Button Event in Jquery Mobile
Applying Classname/Onclick/Onchange Not Working on Custom React Component