客户要求千奇百怪,之前做的在线客服系统,希望收到讯息时加上音效提示,希望把它当作MSN(翻桌),基本上这样还蛮吵的,但在这吵杂声中,顺便把各种拨放音效的方式做个浏览器兼容性的整理。
1.Hyperlink
IE7+(会跳出下载窗口)、Chome、Firefox、Opera
<a href="msg.wav">Play Sound</a>
2.embed
IE7、Chome、Firefox、Opera
<embed src="msg.wav" autostart="false" loop="false">
3.Javascirpt(旧方法)
IE7+、Chome、Firefox、Opera(除IE外,刚进入页面的时候接会拨放一次)
<script>
function PlaySound(soundobj) {
var thissound = eval("document." + soundobj);
thissound.Play();
}
</script>
<input type="button" value="Play Sound" onClick="PlaySound('sound1')">
<embed src="msg.wav" autostart=false width=0 height=0 name="sound1" enablejavascript="true">
4.Javascript(新方法)
IE7+、Chome、Firefox、Opera(除IE外,刚进入页面的时候接会拨放一次)
<script>
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
thissound.Play();
}
</script>
<embed src="msg.wav" autostart="false" width="1" height="1" id="sound1" enablejavascript="true">
<input type="button" value="Play Sound" onClick="EvalSound('sound1')">
5.Background标签
IE Only
<bgsound id="sound">
<script>
function PlaySound(url) {
document.all.sound.src = url;
}
</script>
<input type="button" value="Play Sound" onClick="PlaySound('msg.wav')">
6.Dynamic HTML
IE7+、Chome、Firefox、Opera
<script>
function DHTMLSound(surl) {
document.getElementById("dummyspan").innerHTML =
"<embed src='" + surl + "' hidden=true autostart=true loop=false>";
}
</script>
<span id=dummyspan></span>
<input type="button" value="Play Sound" onClick="DHTMLSound('msg.wav')">
7.HTML5
IE9+(只支援mp3)、Chome、Firefox、Opera
<script>
function EvalSound(soundobj) {
var thissound = document.getElementById(soundobj);
thissound.play();
}
</script>
<audio id="audio1" src="msg.wav" controls preload="auto" autobuffer >
</audio>
<input type="button" value="Play Sound" onClick="EvalSound('audio1')">
结论
如果要再某个事件触发(如Click)又要兼顾兼容性,方法6是比较好的做法