你可以绑定到<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>