需要监听视频的播放进度,并保存当前的播放进度。当页面再次被打开时,我们可以获取保存的播放进度,让视频从上一次的位置开始播放。
-
利用HTML5的 <video>
标签以及它的timeupdate
事件来跟踪视频播放进度。 -
使用Uni-app的生命周期函数,如 onHide
,在用户退出页面时保存当前视频的播放位置。这个可以通过video.currentTime
来获取。 -
使用本地存储技术(如:localStorage或uni.setStorage)来记录用户的播放进度,或者是存到后台数据中。 -
当用户再次打开视频页面时,用 onLoad
生命周期函数来读取用户上次的播放进度,并用video.currentTime
使视频从上次退出的位置开始播放。
参考代码:
<template>
<view class="content">
<video id="video" class="uni-video" controls autoplay poster="https://vu.youku.com/h5_v2/video/playerSea/img/sharelogo.png"></video>
<button @click="playVideo" plain type="default">播放</button>
</view>
</template>
<script>
export default {
data () {
return {
videoContext: null, // 视频对象
timestamp: 0 // 视频上次播放位置
}
},
onLoad() {
this.videoContext = uni.createVideoContext('video');
// 读取localStorage中保存的上次播放位置
var timestampStorage = uni.getStorageSync('timestamp');
if (timestampStorage) {
this.timestamp = timestampStorage;
}
},
onHide() {
// 页面切入后台,暂停视频,并将当前播放时间保存在localStorage中
this.videoContext.pause();
this.videoContext.seek(this.timestamp);
uni.setStorageSync('timestamp', this.timestamp);
},
methods: {
// 播放视频
playVideo() {
if (this.timestamp > 0) {
this.videoContext.seek(this.timestamp);
}
this.videoContext.play();
this.setVideoTime();
},
// 设置视频播放时间
setVideoTime() {
this.videoContext.onTimeUpdate(() => {
this.timestamp = this.videoContext.currentTime;
});
},
},
}
</script>
<style>
.content {
padding: 10px;
}
.uni-video {
width: 100%;
height: 300px;
margin-top: 50px;
display: block;
}
</style>
Vue3的写法:
<template>
<div class="content">
<video :ref="videoRef" controls :src="videoSrc" @timeupdate="updateTime"></video>
<button @click="playVideo" plain type="default">播放</button>
</div>
</template>
<script>
import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const videoSrc = ref('https://path_to_your_video.mp4'); // 视频源
const videoRef = ref(null); // 获得 video DOM 节点的引用
let videoTime = ref(0); // 记录视频播放时间
// 获取视频DOM节点,并获取localStorage中之前保存的播放时间
onMounted(() => {
const storedTime = localStorage.getItem('videoTime');
videoTime = storedTime ? Number(storedTime) : 0; // 若没有值则置零
});
// 在组件卸载时保存播放时间
onUnmounted(() => {
localStorage.setItem('videoTime', videoTime);
});
function updateTime() {
videoTime = videoRef.value.currentTime;
}
// 播放视频,并恢复上次播放的位置
function playVideo() {
videoRef.value.currentTime = videoTime;
videoRef.value.play();
}
return { videoSrc, videoRef, updateTime, playVideo };
},
};
</script>
<style scoped>
.content {
padding: 10px;
}
video {
width: 100%;
height: 300px;
margin-top: 50px;
}
</style>
原文始发于微信公众号(大前端编程教学):uniapp + vue3 h5视频播放保存当前播放记录功能的实现
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/224326.html