適當的音效回饋能顯著提升使用者體驗(如 Windows 清空資源回收筒的紙張聲)。本文提供一個基於 HTML5 <audio>、兼容 IE6-8 使用 <bgsound> 的輕量級音效元件,支援多格式回退、預載、靜音啟動、程式化播放控制。
<a href="#" class="fui-btn">播放</a>
<script>
/* Play sound component */
if (!window.FUI) window.FUI = {};
FUI.soundComponent = function(profile) {
this.profile = {
src: '', // 主音訊檔案路徑
altSrc: '', // 備選格式路徑(瀏覽器支援格式不同)
loop: false // 是否循環(目前未啟用)
};
if (profile) $.extend(this.profile, profile);
this.soundObj = null;
// 簡易 IE 偵測:IE9- 為 true,IE10+ 為 false
this.isIE = !-[1,];
this.init();
};
FUI.soundComponent.prototype = {
init: function() { this._setSrc(); },
_setSrc: function() {
if (this.soundObj) {
if (this.isIE) {
this.soundObj[0].src = this.profile.src;
} else {
this.soundObj[0].innerHTML =
'<source src="' + this.profile.src + '" /> ' +
'<source src="' + this.profile.altSrc + '" />';
}
} else {
if (this.isIE) {
// bgsound 音量 -10000 為靜音,避免載入時誤播
this.soundObj = $(
'<bgsound volume="-10000" loop="1" src="' + this.profile.src + '">'
).appendTo('body');
} else {
this.soundObj = $(
'<audio preload="auto" autobuffer>' +
'<source src="' + this.profile.src + '" />' +
'<source src="' + this.profile.altSrc + '" />' +
'</audio>'
).appendTo('body');
}
}
},
setSrc: function(src, altSrc) {
this.profile.src = src;
if (typeof altSrc !== 'undefined') this.profile.altSrc = altSrc;
this._setSrc();
},
play: function() {
if (!this.soundObj) return;
if (this.isIE) {
this.soundObj[0].volume = 1; // 開啟音量
this.soundObj[0].src = this.profile.src; // 重設 src 觸發播放
} else {
this.soundObj[0].play();
}
}
};
// 使用範例
var sd = new FUI.soundComponent({ src: 'ding.wav', altSrc: 'ding.mp3' });
$('.fui-btn').on('click', function(e) { sd.play(); });
</script>
| 格式 | IE 9 | Firefox 3.5+ | Opera 10.5+ | Chrome 3.0+ | Safari 3.0+ |
|---|---|---|---|---|---|
| Ogg Vorbis | ✗ | ✓ | ✓ | ✓ | ✗ |
| MP3 | ✓ | ✗ | ✗ | ✓ | ✓ |
| WAV | ✗ | ✓ | ✓ | ✓ | ✓ |
策略: 主檔提供 MP3(IE/Safari/Chrome),備檔提供 Ogg(Firefox/Opera),WAV 作為通用備援。
bgsound 預設音量 -10000,避免頁面載入時意外播放。preload="auto" autobuffer 讓瀏覽器提前下載音訊,播放零延遲。<source> 多標籤瀏覽器自動選擇支援格式。!-[1,] 僅針對 IE6-8,IE9+ 走 <audio> 路徑。$ 建立/插入元素,專案需先引入 jQuery。volume 參數與 setVolume() 方法。loop 屬性(HTML5 loop / IE loop="9999")。ended 事件回呼,支援播放完畢觸發邏輯。document.createElement 與 appendChild。