你可以綁定 <audio>
和 <video>
元素的屬性,讓你能夠輕易地(例如)建立自訂播放器 UI,像 AudioPlayer.svelte
。
首先,加入 <audio>
元素及其綁定(我們會使用 src
、duration
和 paused
的簡寫形式)
AudioPlayer
<div class="player" class:paused>
<audio
{src}
bind:currentTime={time}
bind:duration
bind:paused
></audio>
<button
class="play"
aria-label={paused ? 'play' : 'pause'}
></button>
接著,加入一個事件處理器到 <button>
,來切換 paused
AudioPlayer
<button
class="play"
aria-label={paused ? 'play' : 'pause'}
onclick={() => paused = !paused}
></button>
現在我們的音訊播放器有了基本功能。讓我們加入拖曳滑桿以跳到音軌特定部分的功能。在滑桿的 pointerdown
處理器中,有一個 seek
函式,我們可以在這裡更新 time
AudioPlayer
function seek(e) {
const { left, width } = div.getBoundingClientRect();
let p = (e.clientX - left) / width;
if (p < 0) p = 0;
if (p > 1) p = 1;
time = p * duration;
}
當音軌結束時,請友善地倒轉
AudioPlayer
<audio
{src}
bind:currentTime={time}
bind:duration
bind:paused
onended={() => {
time = 0;
}}
></audio>
<audio>
和 <video>
的完整綁定如下 — 七個唯讀綁定...
duration
— 總時間長度,以秒為單位buffered
— 一個{start, end}
物件的陣列seekable
— 同上played
— 同上seeking
— 布林值ended
— 布林值readyState
— 介於(包含)0 和 4 之間的數字
...以及五個雙向綁定
currentTime
— 播放頭的目前位置,以秒為單位playbackRate
— 加速或減速(1
為「正常」)paused
— 這個應該不言自明volume
— 介於 0 和 1 之間的值muted
— 一個布林值,true 表示靜音
影片額外具有唯讀的 videoWidth
和 videoHeight
綁定。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
import AudioPlayer from './AudioPlayer.svelte';
import { tracks } from './tracks.js';
</script>
<div class="centered">
{#each tracks as track}
<AudioPlayer {...track} />
{/each}
</div>
<style>
.centered {
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
gap: 0.5em;
max-width: 40em;
margin: 0 auto;
}
</style>