This tip is for those developers who want to play continuous beep sound as alarm on IE which, unfortunately, does not support WebAudio. SoundManager 2 is the solution to play sounds on web browser. For web browsers that support web audio, it utilizes that just fine. For IE and those not, its falls back on Flash. IE comes installed with a default Flash plugin. To use SoundManager 2, you can download from its official website and put it in web application and included its JavaScript file in the HTML. soundManager
is initialized by calling setup()
. url
is the folder for the SWF Flash programs which are also downloaded from SoundManager 2. Then we set our preferred flashVersion
and whether preferFlash
is the default. onready
callback is set to an anonymous function which is createSound()
with a unique id
, a url
to the Beep.mp3 and whether autoLoad
or autoPlay
should be on by default. We do nothing in onload
function. And volume
is set to 50
. Accepted volume values are 0-100.
<script type="text/javascript" src="script/soundmanager2-nodebug-jsmin.js"></script>
<script type="text/javascript">
var alarm = null;
var stop = false;
soundManager.setup({
url: '/swf/',
flashVersion: 9,
preferFlash: false,
onready: function () {
alarm = soundManager.createSound(
{
id: 'mySound',
url: '/Beep.mp3',
autoLoad: true,
autoPlay: false,
onload: function () {
},
volume: 50
});
}
});
Next we put 2 buttons on HTML to playSound()
and stopSound()
. For our example, I put them in Default.aspx.
<button id="btnPlay" onclick="playSound(); return false;">Play Sound</button>
<button id="btnStop" onclick="stopSound(); return false;">Stop Sound</button>
This is how playSound()
and stopSound()
implements continuous beep. loopSound()
will start playing the beep and in onfinish
callback, loopSound()
is called again unless stop
is true
. In playSound()
, stop
is set to false
and loopSound()
is called. In stopSound()
, stop
is set to true
to break the continuous beep in onfinish
callback and alarm
is stop()
.
var alarm = null;
var stop = false;
function loopSound(sound) {
if (sound === null)
return;
sound.play({
onfinish: function () {
if(stop==false)
loopSound(sound);
}
});
}
function playSound() {
stop = false;
loopSound(alarm);
}
function stopSound() {
stop = true;
if(alarm!==null)
alarm.stop();
}
That's all, folks, for this tip! The code is hosted at GitHub.
History
- 28th June, 2022: Fixed the Newtonsoft.Json vulnerability reported by Github.
- 2nd July, 2019: Initial version