How to play a notification sound on websites? - javascript

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:
What codec should I use?
What's best practice to embed the audio file? (<embed> vs. <object> vs. Flash vs. <audio>)

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.

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.

One more plugin, to play notification sounds on websites: Ion.Sound
Basic Demo
Advanced Demo
Ion.Sound GitHub Page
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");

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(); });

Play cross browser compatible notifications
As adviced by #Tim Tisdall from this post , Check Howler.js Plugin.
Browsers like chrome disables javascript execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.
var sound =new Howl({
src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
'../sounds/rings.aiff'],
autoplay: true,
loop: true
});
sound.play();
Hope helps someone.

if you want calling event on the code The best way to do that is to create trigger because the browser will not respond if the user is not on the page
<button type="button" style="display:none" id="playSoundBtn" onclick="playSound();"></button>
now you can trigger your button when you want to play sound
$('#playSoundBtn').trigger('click');

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!

Use the audio.js which is a polyfill for the <audio> tag with fallback to flash.
In general, look at https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills for polyfills to the HTML 5 APIs.. (it includes more <audio> polyfills)

var audio = new Audio('audio_file.mp3');
function post()
{
var tval=document.getElementById("mess").value;
var inhtml=document.getElementById("chat_div");
inhtml.innerHTML=inhtml.innerHTML+"<p class='me'>Me:-"+tval+"</p>";
inhtml.innerHTML=inhtml.innerHTML+"<p class='demo'>Demo:-Hi! how are you</p>";
audio.play();
}
this code is from talkerscode For complete tutorial visit http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php

I wrote a clean functional method of playing sounds:
sounds = {
test : new Audio('/assets/sounds/test.mp3')
};
sound_volume = 0.1;
function playSound(sound) {
sounds[sound].volume = sound_volume;
sounds[sound].play();
}
function stopSound(sound) {
sounds[sound].pause();
}
function setVolume(sound, volume) {
sounds[sound].volume = volume;
sound_volume = volume;
}

We can just use Audio and an object together like:
var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();
and even adding addEventListener for play and ended

Related

Javascript audio isn't working on mobile devices

The code below works fine on desktop browsers (plays music). But when I try to open the site on any mobile device it doesn't work.
var music = new Audio("mscs/gamemusic.mp3");
function playmusic() {
music.controls = false;
music.loop = false;
music.autoplay = true;
document.body.appendChild(music)
}
I use it in a function when game starts:
function createnewgame() {
...
playmusic();
...
...
}
Does anyone know what's wrong?
Well, this is clearly a browser support issue. According to caniuse, the <audio> element (and js' Audio object is an interface used for it) has known support issues, including
iOS and Chrome on Android do not support autoplay as advised by the specification
and others. Not sure if this can be overcome by some library but since the limitation of autoplay was introduced by design, I wouldn't count on workarounds...
Instead of adding the var "music" to html body, you can try playing the audio directly from JavaScript.
function playmusic() {
music.play();
}
Some mobile browsers support automatic playback of audio, but ios, chrome and others require interactive actions to trigger the sound playback.You can try working with the mute attribute...enter link description here

AppMobi, html5 sound working on simulator and android but not in iphone

Today I get started in appmobi. I was developing a small example to deal with sounds.
I just needed to create a handler to play and stop many sounds.
var audioOn = new Audio('sounds/11.mp3');
audioOn.play();
This code is working in the xdk simulator, also on android devices, but not in my Iphone 5.
The thing is, if I use tag it works on iphone, but I want to use javascript native api to deal with sounds and more.
I have been trying to deal with it with appmobi player library but it comes without controls to stop, resume etc, thats way I want to use native.
Here is part of javascript code :
<script type="text/javascript">
/* This function runs once the page is loaded, but appMobi is not yet active */
var init = function(){
var alarmButton = document.getElementById("alarmButton");
var on = false;
//var audioOn = new Audio('http://rpg.hamsterrepublic.com/wiki-images/3/3e/Heal8-Bit.ogg');
var audioOn = new Audio('sounds/11.mp3');
audioOn.addEventListener('ended', function() {
this.play();
}, false);
var but = function(){
alert("but");
alert(on);
alert(audioOn);
if(!on){
on = true;
audioOn.currentTime = 0;
audioOn.play();
}
else{
on = false;
audioOn.pause();
}
}
//alarmButton.addEventListener("click",but,false);
alarmButton.addEventListener("touchstart",but,false);
alarmButton.addEventListener("tap",but,false);
};
window.addEventListener("load",init,false);
/* This code prevents users from dragging the page */
var preventDefaultScroll = function(event) {
event.preventDefault();
window.scroll(0,0);
return false;
};
document.addEventListener('touchmove', preventDefaultScroll, false);
/* This code is used to run as soon as appMobi activates */
var onDeviceReady=function(){
//Size the display to 768px by 1024px
AppMobi.display.useViewport(768,1024);
//hide splash screen
AppMobi.device.hideSplashScreen();
};
document.addEventListener("appMobi.device.ready",onDeviceReady,false);
function echo(){
alert("clicked");
}
</script>
Thanks a lot
It seems like its not appmobi issue.
I think appmobi lab app for iphone uses safari mobile to run the html5 tests.
So its a safari mobile affair.
It seems play() work when launched by an onclick event. See http://groups.google.com/group/iphonewebdev/browse_thread/thread/91e31ba7ae25e6d4?hl=en
Need to perform some tests...
I have to try this:
http://www.schillmania.com/projects/soundmanager2/
Supporting HTML5 audio can be tedious in modern browsers, let alone
legacy ones. With real-world visitors using browsers ranging from
mobile Safari to IE 6 across a wide range of devices, there can be
many support cases to consider.
SoundManager 2 gives you a single, powerful API that supports both new
and old, using HTML5 audio where supported and optional Flash-based
fallback where needed. Ideally when using SoundManager 2, audio "just
works."

<audio> element not working at all in Safari

I'm trying to add music to a virtual tour application I'm writing in JS and jQuery and so far my code, shown below, works great in Chrome, FF, IE9, and Opera. But in Safari 5.1.7, which is the newest you can get for a Windows machine, it just doesn't work... Through my research of the problem, I know that Safari doesn't autoplay music and it has to be started manually, but when I click the play button, nothing happens. And, btw, the code inspector in Safari shows that my audio tag is there with the music sources so I don't think it has anything to do with the DOM. Any ideas on my problem?
HTML:
<div id="musicBtns">
<p>Music:</p>
<p id="musicPlayBtn">Play</p>
<p>/</p>
<p id="musicPauseBtn">Pause</p>
</div>
My music object in JS:
var Music =
{
musicBtns: $('#musicBtns'),
playBtn: $('#musicPlayBtn'),
pauseBtn: $('#musicPauseBtn'),
isPlaying: false,
init: function()
{
if(!music.includeMusic) // If the client didn't want any music in the tour app, remove the music btns from the DOM
{
this.musicBtns.remove();
}
else // Else, setup the audio element
{
var parent = this;
var audio = $('<audio loop="true">');
if(music.autoplay)
{
audio.attr('autoplay', 'autoplay');
this.isPlaying = true;
this.togglePlayPause();
}
// Add a source elements and appends them to the audio element
this.addSource(audio, music.ogg); // 'music.ogg' is a reference to the path in a JSON file
this.addSource(audio, music.mp3);
this.musicBtns.append(audio);
// Add event listeners for the play/pause btns
this.playBtn.click(function()
{
audio.trigger('play');
parent.isPlaying = true;
parent.togglePlayPause();
});
this.pauseBtn.click(function()
{
audio.trigger('pause');
parent.isPlaying = false;
parent.togglePlayPause();
});
}
},
addSource: function(el, path)
{
el.append($('<source>').attr('src', path));
},
// Add or remove classes depending on the state of play/pause
togglePlayPause: function()
{
if(this.isPlaying)
{
this.playBtn.addClass('underline');
this.pauseBtn.removeClass('underline');
}
else
{
this.playBtn.removeClass('underline');
this.pauseBtn.addClass('underline');
}
}
}
Edit: Could this be a bug in Safari?
So the problem turned out to be with QuickTime. I guess I must of deleted it off of my machine awhile back because I didn't think I needed it. After I re-installed QuickTime, Safari plays music using the audio tag with no problem. Autoplay even works too.
Kinda funny how the champion of native HTML5 audio/video support, doesn't support HTML5 audio/video without a plugin...
In HTML5 video on Safari I had an issue with this where I had to "load" (which, I think, either starts the buffer or loads the whole thing) before I set it to play. This seemed to actually make things work in a few webkit browsers. So something like:
var a = new Audio("file.mp3");
a.load();
a.play();
Worth a try

How to play a mp3 using Javascript? [duplicate]

This question already has answers here:
Play mp3 file using javascript
(3 answers)
Closed 10 years ago.
I have a directory on my website with several mp3's.
I dynamically create a list of them in the website using php.
I also have a drag and drop function associated to them and I can select a list of those mp3 to play.
Now, giving that list, how can I click on a button (Play) and make the website play the first mp3 of the list? (I also know where the music is on the website)
new Audio('<url>').play()
If you want a version that works for old browsers, I have made this library:
// source: https://stackoverflow.com/a/11331200/4298200
function Sound(source, volume, loop)
{
this.source = source;
this.volume = volume;
this.loop = loop;
var son;
this.son = son;
this.finish = false;
this.stop = function()
{
document.body.removeChild(this.son);
}
this.start = function()
{
if (this.finish) return false;
this.son = document.createElement("embed");
this.son.setAttribute("src", this.source);
this.son.setAttribute("hidden", "true");
this.son.setAttribute("volume", this.volume);
this.son.setAttribute("autostart", "true");
this.son.setAttribute("loop", this.loop);
document.body.appendChild(this.son);
}
this.remove = function()
{
document.body.removeChild(this.son);
this.finish = true;
}
this.init = function(volume, loop)
{
this.finish = false;
this.volume = volume;
this.loop = loop;
}
}
Documentation:
Sound takes three arguments. The source url of the sound, the volume (from 0 to 100), and the loop (true to loop, false not to loop).
stop allow to start after (contrary to remove).
init re-set the argument volume and loop.
Example:
var foo = new Sound("url", 100, true);
foo.start();
foo.stop();
foo.start();
foo.init(100, false);
foo.remove();
//Here you you cannot start foo any more
You will probably want to use the new HTML5 audio element to create an Audio object, load the mp3, and play it.
Due to browser inconsistencies, this sample code is a bit lengthly, but it should suit your needs with a bit of tweaking.
//Create the audio tag
var soundFile = document.createElement("audio");
soundFile.preload = "auto";
//Load the sound file (using a source element for expandability)
var src = document.createElement("source");
src.src = fileName + ".mp3";
soundFile.appendChild(src);
//Load the audio tag
//It auto plays as a fallback
soundFile.load();
soundFile.volume = 0.000000;
soundFile.play();
//Plays the sound
function play() {
//Set the current time for the audio file to the beginning
soundFile.currentTime = 0.01;
soundFile.volume = volume;
//Due to a bug in Firefox, the audio needs to be played after a delay
setTimeout(function(){soundFile.play();},1);
}
Edit:
To add Flash support, you would append an object element inside the audio tag.
You can use <audio> HTML5 tag to play audio using JavaScript.
But this is not cross-browser solution. It supported only in modern browsers. For cross-browser compatibility you probably need to use Flash for that (for example jPlayer).
Browsers compatibility table is provided at link I mentioned above.
You could try SoundManager 2: it will transparently handle the <audio> tag wherever it's supported, and use Flash wherever it isn't.
Assuming that the browser supports MP3 playback and is fairly new to support newer JavaScript features, I would suggest taking a look at jPlayer.
You can see a short demo tutorial on how to implement it.
Jquery plugin for audio mp3 player http://www.jplayer.org/0.2.1/demos/
Enjoy it ;)
<html>
<head>
<title>Play my music....</title>
</head>
<body>
<ul>
<li>
<a id="PlayLink" href="http://www.moderntalking.ru/real/music/Modern_Talking-You_Can_Win(DEMO).mp3" onclick="pplayMusic(this, 'music_select');">U Can Win</a>
</li>
<li>
<a id="A1" href="http://www.moderntalking.ru/real/music/Modern_Talking-Brother_Louie(DEMO).mp3" onclick="pplayMusic(this, 'music_select');">Brother Louie</a>
</li>
</ul>
<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script>
</body>
</html>

<Audio> fallback through Javascript

I want to understand how to implement HTML5 <audio> fallback using Javascript...
i.e. I have a div on my page, to which , I dynamically append <embed> tag when "Play audio" link is clicked currently..
i.e. I currently use
function playSound(audioUrl)
{
var x = document.getElementById("playAudio");
x.innerHTML = '<EMBED src="'+audioUrl+'" autostart=true loop=false volume=100 hidden=true>';
}
I want to have the same thing implemented using the HTML5 <audio> tag, But want to fallback to embed when HTML5 audio tag is not supported. How can I implement the same using JS given that the Audio URL is kind of dynamic ?
My intention is it should work on older as well as newer browsers..like IE6,7,8; FF 3,4; Chrome; Safari 4,5 on MAC, Safari on iPad..
You could use Modernizr to detect audio support.
If you don't want to include that library for a simple thing, this should do it...
var audioSupport = document.createElement('audio').hasOwnProperty('src');
jsFiddle.
So that would be...
function playSound(audioUrl) {
var audioSupport = document.createElement('audio').hasOwnProperty('src'),
x = document.getElementById("playAudio");
if (audioSupport) {
var audio = document.createElement('audio');
audio.src = audioUrl;
x.appendChild(audio);
audio.play();
} else {
// Or you could use proper DOM methods...
x.innerHTML = '<EMBED src="' + audioUrl + '" autostart=true loop=false volume=100 hidden=true>';
}
}
jsFiddle.

Categories