萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

用 HTML5 Audio 為網頁添加互動音效:跨瀏覽器完整解決方案

適當的音效回饋能顯著提升使用者體驗(如 Windows 清空資源回收筒的紙張聲)。本文提供一個基於 HTML5 <audio>、兼容 IE6-8 使用 <bgsound> 的輕量級音效元件,支援多格式回退、預載、靜音啟動、程式化播放控制。

核心代碼:FUI.soundComponent

<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 9Firefox 3.5+Opera 10.5+Chrome 3.0+Safari 3.0+
Ogg Vorbis✗✓✓✓✗
MP3✓✗✗✓✓
WAV✗✓✓✓✓
策略: 主檔提供 MP3(IE/Safari/Chrome),備檔提供 Ogg(Firefox/Opera),WAV 作為通用備援。

關鍵實作細節

  • 靜音啟動:IE bgsound 預設音量 -10000,避免頁面載入時意外播放。
  • 預載入:preload="auto" autobuffer 讓瀏覽器提前下載音訊,播放零延遲。
  • 多來源回退:<source> 多標籤瀏覽器自動選擇支援格式。
  • IE9+ 統一用 Audio:偵測邏輯 !-[1,] 僅針對 IE6-8,IE9+ 走 <audio> 路徑。
  • jQuery 依賴:元件使用 $ 建立/插入元素,專案需先引入 jQuery。

擴充建議

  1. 加入 volume 參數與 setVolume() 方法。
  2. 實作 loop 屬性(HTML5 loop / IE loop="9999")。
  3. 支援多音效實例管理(音效池),避免重複建立 DOM 節點。
  4. 加入 ended 事件回呼,支援播放完畢觸發邏輯。
  5. 若不想依賴 jQuery,可改用原生 document.createElement 與 appendChild。
copyright © 萬盛學電腦網 all rights reserved