此提示适用于那些想要在IE上播放连续蜂鸣声作为警报的开发人员,不幸的是,IE不支持WebAudio。SoundManager 2是在Web浏览器上播放声音的解决方案。对于支持Web音频的网络浏览器,它可以很好地利用这一点。对于IE和那些不是IE的人来说,它回到了Flash。IE随默认的Flash插件一起安装。要使用SoundManager 2,您可以从其官方网站下载并将其放入Web应用程序中,并将其JavaScript文件包含在通过HTML 中。soundManager通过调用setup()来初始化。url是SWF Flash程序的文件夹,这些程序也是从SoundManager 2下载的。然后我们设置首选的flashVersion以及preferFlash是否是默认的。onready回调被设置为一个匿名函数,它是createSound(),具有唯一的id,一个Beep.mp3的url,以及默认情况下是否应该打开autoLoad或autoPlay。我们在onload函数中没有做任何的事情。volume设置为50。可接受的音量值为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, // optional: shiny features (default = 8)
// optional: ignore Flash where possible, use 100% HTML5 mode
preferFlash: false,
onready: function () {
// Ready to use; soundManager.createSound() etc. can now be called.
alarm = soundManager.createSound(
{
id: 'mySound',
url: '/Beep.mp3',
autoLoad: true,
autoPlay: false,
onload: function () {
// to check whether sound is loaded
//alert('The sound ' + this.id + ' loaded!');
},
volume: 50
});
}
});
接下来,我们在HTML上放置2个按钮来playSound()和stopSound()。对于我们的示例,我将它们放在Default.aspx 中。
<button id="btnPlay" onclick="playSound(); return false;">Play Sound</button>
<button id="btnStop" onclick="stopSound(); return false;">Stop Sound</button>
这是playSound()和stopSound()如何实现连续的蜂鸣声。loopSound()将开始播放蜂鸣声和onfinish回调,再次调用loopSound()除非stop为true。在playSound()中,stop被设置为false并且loopSound()被调用。在stopSound()中,stop设置为true以中断onfinish回调中的连续的蜂鸣而alarm是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; // stop looping
if(alarm!==null)
alarm.stop();
}
伙计们,这就是这个提示的全部内容!代码托管在GitHub 上。
https://www.codeproject.com/Tips/5161202/Continuous-Beep-on-Webpage-with-SoundManager-2