[HTML]網頁音效播放相容性整理
客戶要求千奇百怪,之前做的線上客服系統,希望收到訊息時加上音效提示,希望把它當作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是比較好的做法
--
Reference
http://www.phon.ucl.ac.uk/home/mark/audio/play.htm
http://www.w3schools.com/html/html5_audio.asp