萬盛學電腦網

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

HTML5 多媒體組件實戰(三):自訂影音播放器控制介面開發

系列回顧與目標

前兩篇介紹 <video>、<audio> 原生 controls 屬性,但各瀏覽器渲染風格不一(字體、顏色、按鈕佈局皆不同)。本篇教學如何用 HTML/CSS/JS 打造跨瀏覽器風格統一、功能可擴展的自訂播放器。

第一步:定義媒體元素並關閉原生控制列

<video id="video" width="640" height="360" poster="poster.jpg">
  <source src="video.mp4" type="video/mp4">
  <source src="video.webm" type="video/webm">
  <track kind="captions" src="subtitles.vtt" srclang="zh" label="中文" default>
</video>

<script>
const video = document.getElementById('video');
video.controls = false; // 關鍵:關閉原生 UI,改由自訂控制
</script>

保留 controls 屬性於標籤中,再用 JS 關閉,確保 JS 失效時仍有基本播放能力(漸進增強)。

第二步:建構自訂控制列 HTML 結構

<div class="player-controls">
  <button id="playPause" aria-label="播放/暫停"><svg class="icon-play">…</svg><svg class="icon-pause" hidden>…</svg></button>
  <div class="progress-bar" role="slider" aria-label="播放進度" tabindex="0">
    <div class="progress-buffered"></div>
    <div class="progress-played"></div>
    <div class="progress-handle"></div>
  ></div>
  <span id="currentTime">0:00</span> / <span id="duration">0:00</span>
  <button id="mute" aria-label="靜音"><svg class="icon-volume">…</svg><svg class="icon-muted" hidden>…</svg></button>
  <input type="range" id="volume" min="0" max="1" step="0.1" value="1" aria-label="音量">
  <button id="fullscreen" aria-label="全螢幕"><svg class="icon-fullscreen">…</svg></button>
  <button id="pip" aria-label="畫中畫"><svg class="icon-pip">…</svg></button>
  <select id="playbackRate" aria-label="播放速度">
    <option value="0.5">0.5×</option>
    <option value="1" selected>1×</option>
    <option value="1.5">1.5×</option>
    <option value="2">2×</option>
  </select>
</div>

第三步:核心 JS 邏輯(事件綁定與狀態同步)


const btnPlayPause = document.getElementById('playPause');
const progressBar = document.querySelector('.progress-bar');
const progressPlayed = document.querySelector('.progress-played');
const progressBuffered = document.querySelector('.progress-buffered');
const currentTimeEl = document.getElementById('currentTime');
const durationEl = document.getElementById('duration');
const btnMute = document.getElementById('mute');
const volumeSlider = document.getElementById('volume');
const btnFullscreen = document.getElementById('fullscreen');
const btnPip = document.getElementById('pip');
const rateSelect = document.getElementById('playbackRate');

// 格式化時間
function fmt(t) { return `${(t/60)|0}:${(t%60).toString().padStart(2,'0')}`; }

// 播放/暫停切換
btnPlayPause.onclick = () => video.paused ? video.play() : video.pause();
video.onplay = () => { btnPlayPause.querySelector('.icon-play').hidden = true; btnPlayPause.querySelector('.icon-pause').hidden = false; };
video.onpause = () => { btnPlayPause.querySelector('.icon-play').hidden = false; btnPlayPause.querySelector('.icon-pause').hidden = true; };

// 時間更新
video.ontimeupdate = () => {
  currentTimeEl.textContent = fmt(video.currentTime);
  progressPlayed.style.width = (video.currentTime / video.duration) * 100 + '%';
};
video.onloadedmetadata = () => durationEl.textContent = fmt(video.duration);

// 緩衝進度
video.onprogress = () => {
  if (video.buffered.length) {
    progressBuffered.style.width = (video.buffered.end(0) / video.duration) * 100 + '%';
  }
};

// 進度條拖曳求值
let dragging = false;
progressBar.addEventListener('mousedown', e => { dragging = true; seek(e); });
window.addEventListener('mousemove', e => dragging && seek(e));
window.addEventListener('mouseup', () => dragging = false);
function seek(e) {
  const rect = progressBar.getBoundingClientRect();
  const pct = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
  video.currentTime = pct * video.duration;
}

// 音量與靜音
volumeSlider.oninput = () => { video.volume = volumeSlider.value; video.muted = false; syncMuteIcon(); };
btnMute.onclick = () => { video.muted = !video.muted; syncMuteIcon(); };
function syncMuteIcon() {
  btnMute.querySelector('.icon-volume').hidden = video.muted || video.volume === 0;
  btnMute.querySelector('.icon-muted').hidden = !video.muted && video.volume > 0;
}

// 全螢幕與畫中畫
btnFullscreen.onclick = () => {
  if (document.fullscreenElement) document.exitFullscreen();
  else video.requestFullscreen();
};
btnPip.onclick = async () => {
  try { await video.requestPictureInPicture(); }
  catch (err) { console.error('PiP 不支援', err); }
}

// 播放速度
rateSelect.onchange = () => video.playbackRate = parseFloat(rateSelect.value);

// 鍵盤無障礙支援
video.addEventListener('keydown', e => {
  if (e.code === 'Space') { e.preventDefault(); video.paused ? video.play() : video.pause(); }
  if (e.code === 'ArrowRight') video.currentTime = Math.min(video.duration, video.currentTime + 5);
  if (e.code === 'ArrowLeft') video.currentTime = Math.max(0, video.currentTime - 5);
  if (e.code === 'ArrowUp') video.volume = Math.min(1, video.volume + 0.1);
  if (e.code === 'ArrowDown') video.volume = Math.max(0, video.volume - 0.1);
});

CSS 關鍵樣式(SCSS 片段)

.player-controls {
  display: flex; align-items: center; gap: 0.5rem;
  padding: 0.5rem 1rem; background: rgba(0,0,0,0.7); color: #fff;
  position: absolute; bottom: 0; left: 0; right: 0;
  opacity: 0; transition: opacity 0.2s;
}
video:hover + .player-controls, .player-controls:hover { opacity: 1; }
.progress-bar { flex: 1; height: 4px; background: #444; border-radius: 2px; position: relative; cursor: pointer; }
.progress-buffered { position: absolute; top: 0; bottom: 0; left: 0; background: rgba(255,255,255,0.3); border-radius: 2px; }
.progress-played { position: absolute; top: 0; bottom: 0; left: 0; background: #e50914; border-radius: 2px; }
.progress-handle { position: absolute; top: 50%; transform: translate(-50%, -50%); width: 12px; height: 12px; background: #fff; border-radius: 50%; opacity: 0; transition: opacity 0.1s; }
.progress-bar:hover .progress-handle { opacity: 1; }

進階擴展方向

  • 鍵盤快捷鍵:空白鍵播放/暫停、左右鍵 ±5 秒、上下鍵音量、F 全螢幕、M 靜音
  • 觸控手勢:左右滑動求值、上下滑動音量/亮度(參考 nPlayer/Infuse 交互)
  • 字幕樣式自訂:::cue 偽元素控制字幕字體、顏色、背景
  • Media Session API:整合系統鎖屏/通知中心/耳機按鈕控制
  • DRM 內容保護:EME + Clear Key / Widevine / PlayReady

自訂播放器賦予品牌一致性體驗,亦是通往 PWA、離線播放、串流媒體商業化的基石。

copyright © 萬盛學電腦網 all rights reserved