萬盛學電腦網

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

HTML5 <audio> 嵌入音訊完整指南:格式相容、預載策略、無障礙與自訂播放器

HTML5 <audio> 元素提供**原生、無外掛**的音訊播放能力。本文詳細說明支援格式、屬性完整表、預載策略、跨瀏覽器相容寫法、無障礙需求,並提供**自訂播放器元件**與 **Web Audio API 進階應用**範例。

支援格式與瀏覽器相容性 (2024)

格式MIME 型別ChromeFirefoxSafariEdge備註
MP3audio/mpeg✅✅✅✅相容性最佳,授權免費 (專利已過期)
AAC (MP4/M4A)audio/mp4, audio/aac✅✅✅✅Apple 生態首選,品質優於 MP3 同位元率
Ogg Opusaudio/ogg; codecs=opus✅✅✅ (14+)✅開放免費、壓縮效率最高、推薦作為備用來源
WAVaudio/wav✅✅✅✅無損、體積大、不適合網路傳輸
FLACaudio/flac✅✅✅✅無損壓縮、體積較 WAV 小約 50%

**建議雙來源策略**:<source src="audio.mp3" type="audio/mpeg"> + <source src="audio.opus" type="audio/ogg; codecs=opus">,覆蓋 99.9% 瀏覽器。

<audio> 完整屬性表

屬性類型說明
srcURL單一音訊來源 (建議改用 <source> 多來源)
controlsBoolean顯示瀏覽器原生播放控制列 (播放/暫停、音量、進度條)
autoplayBoolean自動播放 (現代瀏覽器需靜音或使用者互動後才生效)
loopBoolean循環播放
mutedBoolean預設靜音 (配合 autoplay 可繞過自動播放政策)
preload'none' | 'metadata' | 'auto'預載策略:none=不預載、metadata=只載入中繼資料、auto=瀏覽器決定 (通常完整載入)
crossorigin'anonymous' | 'use-credentials'跨域請求時的 CORS 模式,需搭配伺服器標頭
controlslist'nodownload' | 'noremoteplayback' | 'nofullscreen'隱藏原生控制列特定按鈕 (Chrome/Edge 支援)

標準嵌入範本 (含無障礙)

<audio controls controlslist="nodownload" preload="metadata">
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.opus" type="audio/ogg; codecs=opus">
  <track kind="captions" src="audio-captions.vtt" srclang="zh-Hant" label="繁體中文字幕" default>
  <!-- 降級內容:不支援 audio 的極舊瀏覽器 -->
  <p>您的瀏覽器不支援 HTML5 音訊播放。
    <a href="audio.mp3" download>下載 MP3 檔案</a>
  </p>
</audio>

預載策略選擇指南

場景preload 值理由
音樂播放器、播客、主要內容auto 或預設使用者高機率播放,預載完整檔案可即時開始
語音提示、音效、背景音樂metadata只需時長/尺寸資訊,不佔用頻寬下載內容
隱藏音訊、條件式播放 (如遊戲音效)none完全不預載,按需動態 src 載入
行動裝置流量敏感場景metadata + 使用者互動後 load()尊重流量、降低啟動延遲

自訂播放器元件 (Vanilla JS, 無依賴)

/**
 * CustomAudioPlayer - 可樣式化、無障礙、支援鍵盤操作
 * HTML 結構需包含:.player-root > audio + .controls > [data-action]
 */
class CustomAudioPlayer {
  constructor(rootEl) {
    this.root = rootEl;
    this.audio = rootEl.querySelector('audio');
    this.bindEvents();
    this.updateUI();
  }

  bindEvents() {
    // 原生事件映射到 UI 更新
    ['play', 'pause', 'timeupdate', 'loadedmetadata', 'ended', 'error', 'volumechange'].forEach(evt => {
      this.audio.addEventListener(evt, () => this.updateUI());
    });
    // 控制按鈕
    this.root.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', () => this[btn.dataset.action]());
    });
    // 進度條拖曳
    const seekBar = this.root.querySelector('[data-seek]');
    seekBar?.addEventListener('input', e => this.seek(e.target.value));
    // 鍵盤支援
    this.root.addEventListener('keydown', e => {
      if (e.code === 'Space') { e.preventDefault(); this.togglePlay(); }
      if (e.code === 'ArrowRight') this.seekRelative(10);
      if (e.code === 'ArrowLeft') this.seekRelative(-10);
      if (e.code === 'ArrowUp') this.volumeRelative(0.1);
      if (e.code === 'ArrowDown') this.volumeRelative(-0.1);
    });
  }

  togglePlay() { this.audio.paused ? this.audio.play() : this.audio.pause(); }
  seek(percent) { this.audio.currentTime = this.audio.duration * percent / 100; }
  seekRelative(sec) { this.audio.currentTime = Math.max(0, Math.min(this.audio.duration, this.audio.currentTime + sec)); }
  volumeRelative(delta) { this.audio.volume = Math.max(0, Math.min(1, this.audio.volume + delta)); }

  updateUI() {
    const { paused, currentTime, duration, volume, muted } = this.audio;
    this.root.querySelector('[data-action="togglePlay"]')?.setAttribute('aria-label', paused ? '播放' : '暫停');
    this.root.querySelector('[data-seek]')?.value = duration ? (currentTime / duration * 100) : 0;
    this.root.querySelector('[data-current]')?.textContent = this.formatTime(currentTime);
    this.root.querySelector('[data-duration]')?.textContent = this.formatTime(duration);
    this.root.querySelector('[data-volume]')?.value = volume * 100;
    this.root.classList.toggle('playing', !paused);
    this.root.classList.toggle('muted', muted);
  }

  formatTime(sec) {
    if (isNaN(sec)) return '0:00';
    const m = Math.floor(sec / 60), s = Math.floor(sec % 60);
    return `${m}:${s.toString().padStart(2, '0')}`;
  }

  static init(selector = '.audio-player') {
    document.querySelectorAll(selector).forEach(el => new CustomAudioPlayer(el));
  }
}

// HTML 範本
/*
0:00 0:00
*/ // 初始化 CustomAudioPlayer.init();

Web Audio API 進階應用:音效合成、視覺化、空間音訊

// 基礎音效播放 (低延遲、可疊加)
const ctx = new (window.AudioContext || window.webkitAudioContext)();
async function playSound(url) {
  const resp = await fetch(url);
  const arrayBuffer = await resp.arrayBuffer();
  const audioBuffer = await ctx.decodeAudioData(arrayBuffer);
  const source = ctx.createBufferSource();
  source.buffer = audioBuffer;
  source.connect(ctx.destination);
  source.start(0);
}

// 視覺化:頻譜圖
const analyser = ctx.createAnalyser();
analyser.fftSize = 256;
const dataArray = new Uint8Array(analyser.frequencyBinCount);
source.connect(analyser).connect(ctx.destination);
function render() {
  requestAnimationFrame(render);
  analyser.getByteFrequencyData(dataArray);
  // 繪製到 Canvas...
}
render();

// 空間音訊 (PannerNode)
const panner = ctx.createPanner();
panner.panningModel = 'HRTF';
panner.positionX.setValueAtTime(1, ctx.currentTime); // 右側
source.connect(panner).connect(ctx.destination);

自動播放政策應對清單

  1. **靜音自動播放**:<audio autoplay muted> 幾乎所有瀏覽器允許。
  2. **使用者互動解鎖**:在 document.body 首次 click/touchstart/keydown 時呼叫 audio.play() 並 pause(),後續即可自由播放。
  3. **Media Session API**:整合系統媒體控制中心 (鎖屏、通知欄、耳機按鈕)。

結語

<audio> 是 Web 音訊的基石。**雙來源 MP3+Opus**、**preload 策略**、**無障礙字幕**、**自訂播放器**與 **Web Audio API** 進階能力,共同構建現代 Web 音訊體驗。記住:尊重使用者自動播放偏好、提供音量/靜音控制、優化行動裝置頻寬,才是專業音訊應用的標配。

copyright © 萬盛學電腦網 all rights reserved