如果你想让视频从上一次播放的位置继续播放,而不是每次都从头开始,你可以在页面的 data
中添加一个变量来存储视频的当前播放位置,然后在 onPlayButtonTap
函数中使用这个位置来设置视频的播放进度。
首先,在页面的 data
中添加一个新的变量,例如 currentTime
:
data: {
// ...
currentTime: 0
},
然后,修改 onPlayButtonTap
函数如下:
onPlayButtonTap: function() {
// 设置 showVideo 为 true,让视频播放器显示出来
this.setData({
showVideo: true
}, () => {
// 获取视频上下文对象
const videoContext = wx.createVideoContext('myVideo', this);
// 延迟 100 毫秒,确保视频组件已经完全加载
setTimeout(() => {
// 将视频的当前播放时间设置为上一次的播放位置
videoContext.seek(this.data.currentTime);
// 调用视频上下文对象的 play 方法来播放视频
videoContext.play();
}, 100);
});
},
在这个修改后的 onPlayButtonTap
函数中,我们不再将视频的当前播放时间设置为 0,而是设置为 this.data.currentTime
,也就是上一次播放的位置。
最后,我们需要在视频播放过程中不断更新 currentTime
的值。你可以通过监听视频的 timeupdate
事件来实现这一点。在 WXML 中,为 <video>
组件添加 bindtimeupdate
属性:
<video
object-fit="contain"
referrer-policy="origin"
wx:if="{{showVideo}}"
id="myVideo"
show-mute-btn="{{true}}"
muted="{{false}}"
src="{{spu.video}}"
controls
class="video-player"
binderror="onVideoError"
bindtimeupdate="onVideoTimeUpdate"
></video>
然后,在 JavaScript 中添加 onVideoTimeUpdate
函数:
onVideoTimeUpdate: function(e) {
this.setData({
currentTime: e.detail.currentTime
});
},
在 onVideoTimeUpdate
函数中,我们将视频的当前播放时间 e.detail.currentTime
存储到 currentTime
变量中。
通过这些修改,当用户点击自定义播放按钮时,视频将从上一次播放的位置继续播放,而不是每次都从头开始。