在網頁加入音效回饋(按鈕點擊、通知提示、遊戲音效)能顯著提升使用者體驗。HTML5 <audio> 元素提供原生播放能力,但需處理格式相容、預載策略、舊版 IE 降級、多實例管理等細節。本文提供一個**可直接生產環境使用的音效元件封裝**,支援現代瀏覽器與 IE9+。
| 挑戰 | 解決方案 |
|---|---|
| 音訊格式瀏覽器支援度不一 | 提供 **雙格式來源**(MP3 + OGG/WebM),瀏覽器自動選擇支援格式 |
| IE9- 不支援 <audio> | 降級使用專屬 <bgsound> 元素 |
| 頁面載入即播放(驚嚇使用者) | preload="auto" + bgsound volume="-10000" 靜音預載,播放時才開啟音量 |
| 頻繁觸發需低延遲播放 | 預先建立 Audio 實例、preload="auto"、audio.currentTime = 0 重播 |
| 多音效並發管理 | 元件化封裝,每個音效獨立實例,支援 play()、stop()、setSrc() |
/**
* SoundEffect - 輕量級 HTML5 音效元件
* 支援:現代瀏覽器 (audio) + IE9+ (bgsound)
* 依賴:無 (原生 JS),可選擇性搭配 jQuery 選取觸發元素
*/
class SoundEffect {
/**
* @param {Object} options
* @param {string} options.src - 主要音訊來源 (MP3 推薦)
* @param {string} [options.altSrc] - 備用來源 (OGG/WebM)
* @param {boolean} [options.loop=false] - 是否循環
* @param {number} [options.volume=1] - 音量 0~1
*/
constructor({ src, altSrc = '', loop = false, volume = 1 } = {}) {
this.src = src;
this.altSrc = altSrc;
this.loop = loop;
this.volume = volume;
this._audio = null;
this._isIE = !![document.documentMode]; // IE9-11 為真
this._init();
}
_init() {
if (this._isIE) {
// IE 使用 bgsound,音量 -10000 為靜音
this._audio = document.createElement('bgsound');
this._audio.volume = -10000;
this._audio.loop = this.loop ? 9999 : 1;
this._audio.src = this.src;
document.body.appendChild(this._audio);
} else {
this._audio = document.createElement('audio');
this._audio.preload = 'auto';
this._audio.loop = this.loop;
this._audio.volume = this.volume;
// 多來源回退
this._audio.innerHTML = `
<source src="${this.src}" type="audio/mpeg">
${this.altSrc ? `<source src="${this.altSrc}" type="audio/ogg">` : ''}
`;
document.body.appendChild(this._audio);
}
}
/** 更新音效來源 */
setSrc(src, altSrc) {
this.src = src;
if (altSrc !== undefined) this.altSrc = altSrc;
this._updateSrc();
}
_updateSrc() {
if (this._isIE) {
this._audio.src = this.src;
} else {
this._audio.innerHTML = `
<source src="${this.src}" type="audio/mpeg">
${this.altSrc ? `<source src="${this.altSrc}" type="audio/ogg">` : ''}
`;
this._audio.load(); // 重新載入
}
}
/** 播放音效 */
play() {
if (!this._audio) return;
if (this._isIE) {
this._audio.volume = 0; // 0 dB = 正常音量 (bgsound 以 0 為最大)
this._audio.src = this.src; // 重設 src 觸發重播
} else {
this._audio.currentTime = 0; // 重置播放位置
this._audio.play().catch(err => {
// 自動播放政策阻擋時靜默失敗,避免主控台報錯
console.warn('Audio play blocked by autoplay policy:', err);
});
}
}
/** 停止播放 */
stop() {
if (!this._audio) return;
if (this._isIE) {
this._audio.volume = -10000;
} else {
this._audio.pause();
this._audio.currentTime = 0;
}
}
/** 銷毀元件,釋放資源 */
destroy() {
if (this._audio) {
this._audio.remove();
this._audio = null;
}
}
}
// UMD 掛載
if (typeof module !== 'undefined' && module.exports) module.exports = SoundEffect;
else if (typeof define === 'function' && define.amd) define([], () => SoundEffect);
else window.SoundEffect = SoundEffect;
<!-- HTML -->
<button class="btn-click">點擊播放音效</button>
<script>
// 建立音效實例(建議在應用啟動時預先建立,完成預載)
const clickSfx = new SoundEffect({
src: '/assets/sfx/click.mp3',
altSrc: '/assets/sfx/click.ogg',
volume: 0.6
});
// 綁定觸發
document.querySelector('.btn-click').addEventListener('click', () => clickSfx.play());
// 頁面卸載時清理
window.addEventListener('beforeunload', () => clickSfx.destroy());
</script>
currentTime=0 造成截斷。AudioContext + AudioBufferSourceNode,延遲 < 10ms。catch 阻擋錯誤,建議在使用者首次點擊/按鍵時預先 play() 並 pause() 解鎖。localStorage,尊重使用者選擇。| 格式 | 編碼 | 瀏覽器支援 | 建議用途 |
|---|---|---|---|
| MP3 | MPEG-1 Layer 3 | 全瀏覽器 ✅ | 主要來源,相容性最高 |
| OGG Opus | Opus | Chrome, Firefox, Edge, Safari 14+ ✅ | 備用來源,壓縮品質最佳 |
| WebM Opus | Opus | Chrome, Firefox, Edge ✅ | 備用來源,開放免費 |
| AAC (MP4) | AAC | Safari, Chrome, Edge ✅ | Apple 生態最佳相容 |
**建議雙來源:MP3 + OGG Opus**,覆蓋 99%+ 瀏覽器。