Svelte基础
Svelte高阶
上下文API
特殊元素
接下来
SvelteKit基础
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
<audio>和<video>这样的多媒体元素也是可以绑定属性值的, 就像AudioPlayer.svelte演示的那样对播放界面做些定制化.
You can bind to properties of
<audio>and<video>elements, making it easy to (for example) build custom player UI, likeAudioPlayer.svelte.
首先添加一个<audio>元素并绑定属性(使用了简写形式绑定了属性src, duration和paused):
First, add the
<audio>element along with its bindings (we’ll use the shorthand form forsrc,durationandpaused):
<div class={['player', { paused }]}>
<audio
{src}
bind:currentTime={time}
bind:duration
bind:paused
></audio>
<button
class="play"
aria-label={paused ? 'play' : 'pause'}
></button>接下来为按钮<button>添加事件处理器用于切换播放(play)和暂停(paused):
Next, add an event handler to the
<button>that togglespaused:
<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
pointerdownhandler there’s aseekfunction, where we can updatetime:
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> 支持的绑定包括:7个 只读 绑定:
duration— 总时长,以秒为单位buffered— 包含{start, end}对象的数组seekable— 同上played— 同上seeking— 布尔值ended— 布尔值readyState— 介于(包含)0 到 4 之间的数字
5个 双向 绑定:
currentTime— 当前播放位置,以秒为单位playbackRate— 加速或减速(1为“正常”)paused— 是否暂停volume— 介于 0 到 1 之间的值muted— 布尔值,true表示静音
视频还额外具有只读的 videoWidth 和 videoHeight 绑定。
The complete set of bindings for
<audio>and<video>is as follows — seven readonly bindings...
duration— the total duration, in secondsbuffered— an array of{start, end}objectsseekable— dittoplayed— dittoseeking— booleanended— booleanreadyState— number between (and including) 0 and 4
...and five two-way bindings:
currentTime— the current position of the playhead, in secondsplaybackRate— speed up or slow down (1is ‘normal’)paused— this one should be self-explanatoryvolume— a value between 0 and 1muted— a boolean value where true is muted
Videos additionally have readonly
videoWidthandvideoHeightbindings.
<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>