你可以绑定到 <audio>
和 <video>
元素的属性,从而轻松(例如)构建自定义播放器 UI,如 AudioPlayer.svelte
。
¥You can bind to properties of <audio>
and <video>
elements, making it easy to (for example) build custom player UI, like AudioPlayer.svelte
.
首先,添加 <audio>
元素及其绑定(我们将使用 src
、duration
和 paused
的简写形式):
¥First, add the <audio>
element along with its bindings (we’ll use the shorthand form for src
, duration
and paused
):
<div class={['player', { paused }]}>
<audio
{src}
bind:currentTime={time}
bind:duration
bind:paused
></audio>
<button
class="play"
aria-label={paused ? 'play' : 'pause'}
></button>
接下来,向 <button>
添加一个事件处理程序来切换 paused
:
¥Next, add an event handler to the <button>
that toggles paused
:
<button
class="play"
aria-label={paused ? 'play' : 'pause'}
onclick={() => paused = !paused}
></button>
我们的音频播放器现在具有基本功能。让我们通过拖动滑块添加查找轨道特定部分的功能。在滑块的 pointerdown
处理程序中有一个 seek
函数,我们可以在其中更新 time
:
¥Our audio player now has basic functionality. Let’s add the ability to seek to a specific part of a track by dragging the slider. Inside the slider’s pointerdown
handler there’s a seek
function, where we can update time
:
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;
}
曲目结束时,请善意地倒带:
¥When the track ends, be kind — rewind:
<audio
{src}
bind:currentTime={time}
bind:duration
bind:paused
onended={() => {
time = 0;
}}
></audio>
<audio>
和 <video>
的完整绑定集如下 - 七个只读绑定...
¥The complete set of bindings for <audio>
and <video>
is as follows — seven readonly bindings...
duration
— 总持续时间,以秒为单位¥
duration
— the total duration, in secondsbuffered
—{start, end}
对象数组¥
buffered
— an array of{start, end}
objectsseekable
— 同上¥
seekable
— dittoplayed
— 同上¥
played
— dittoseeking
— 布尔值¥
seeking
— booleanended
— 布尔值¥
ended
— booleanreadyState
— 0 到 4 之间的数字(含)¥
readyState
— number between (and including) 0 and 4
...和五个双向绑定:
¥...and five two-way bindings:
currentTime
— 播放头的当前位置(以秒为单位)¥
currentTime
— the current position of the playhead, in secondsplaybackRate
— 加速或减速(1
是 ‘normal’)¥
playbackRate
— speed up or slow down (1
is ‘normal’)paused
— 这个应该是不言自明的¥
paused
— this one should be self-explanatoryvolume
— 0 到 1 之间的值¥
volume
— a value between 0 and 1muted
— 布尔值,其中 true 被静音¥
muted
— a boolean value where true is muted
视频还具有只读 videoWidth
和 videoHeight
绑定。
¥Videos additionally have readonly videoWidth
and videoHeight
bindings.
<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>