Plyr 如何循环播放指定时间段并显示分段进度?
数据小许
可以循环播放指定区间。不过,设置 currentTime 只会改变播放位置,不会调整 Plyr 时间轴的范围。若要让界面显示 02
用 timeupdate 限定循环区间
02
和 02 分别是 153 秒和 155 秒。下面的代码通过原生<video> 的 timeupdate 事件检查播放位置;播放越过区间边界时,会跳回起点:
<vue-plyr :options="videoOptions">
<video
ref="videoEl"
controls
crossorigin
playsinline
@timeupdate="onTimeUpdate"
>
<source src="/public/myvideo.mp4" type="video/mp4" />
</video>
</vue-plyr>
<button @click="setLoop(153, 155)">
循环播放 02:33–02:35
</button>
<input
type="range"
:min="loopStart"
:max="loopEnd"
step="0.01"
:value="currentTime"
aria-label="分段播放进度"
@input="seekSegment"
/>
import { ref } from 'vue'
const videoEl = ref<HTMLVideoElement | null>(null)
const loopStart = ref(0)
const loopEnd = ref(0)
const isLooping = ref(false)
const currentTime = ref(0)
const setLoop = (start: number, end: number) => {
if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) {
return
}
loopStart.value = start
loopEnd.value = end
isLooping.value = true
if (videoEl.value) {
videoEl.value.currentTime = start
currentTime.value = start
}
}
const onTimeUpdate = () => {
const video = videoEl.value
if (!video) return
if (isLooping.value && (video.currentTime < loopStart.value || video.currentTime >= loopEnd.value)) {
video.currentTime = loopStart.value
}
currentTime.value = video.currentTime
}
const seekSegment = (event: Event) => {
const video = videoEl.value
const input = event.target as HTMLInputElement
if (!video) return
const time = Number(input.value)
video.currentTime = Math.min(loopEnd.value, Math.max(loopStart.value, time))
currentTime.value = video.currentTime
}
调用 setLoop(153, 155) 后,视频会跳到 02
关于 Plyr 自带时间轴
Plyr 自带的时间轴仍按视频总时长显示。自定义滑块可以与它并排显示分段进度;如果要用自定义滑块替代 Plyr 时间轴,需要自行实现或调整播放器控件,并处理滑块位置与视频时间的映射。只修改 currentTime 不会改变原时间轴的刻度范围。
保留 Plyr 自带控件时,用户仍可跳到区间外;事件处理会在检测到播放位置超出区间后将其跳回起点。如果不希望用户看到或操作整段视频的时间轴,可以改用自定义进度控件,并按需调整播放器控件配置。
备注:内容仅供参考。
