vue实现自定义H5视频播放器的方法步骤

2020-06-13 10:27:00易采站长站整理


// 点击播放 & 暂停按钮
clickPlayBtn() {
if (this.state.isLoading) return;
this.isFirstTouch = false;
this.state.playing = !this.state.playing;
this.state.isEnd = false;
if (this.$video) {
// 播放状态
if (this.state.playing) {
try {
this.$video.play();
this.isPauseTouch = false;
// 监听缓存进度
this.$video.addEventListener("progress", e => {
this.getLoadTime();
});
// 监听播放进度
this.$video.addEventListener(
"timeupdate",
throttle(this.getPlayTime, 100, 1)
);
// 监听结束
this.$video.addEventListener("ended", e => {
// 重置状态
this.state.playing = false;
this.state.isEnd = true;
this.state.controlBtnShow = true;
this.video.displayTime = "00:00";
this.video.progress.current = 0;
this.$video.currentTime = 0;
});
} catch (e) {
// 捕获url异常出现的错误
}
}
// 停止状态
else {
this.isPauseTouch = true;
this.$video.pause();
}
}
},

视频控制条显示和隐藏

这里需要加两个开关; 首次触屏和暂停触屏; 做一下显示处理即可


// 触碰播放区
touchEnterVideo() {
if (this.isFirstTouch) return;
if (this.hideTimer) {
clearTimeout(this.hideTimer);
this.hideTimer = null;
}
this.state.controlBtnShow = true;
this.state.controlBarShow = true;
},
// 离开播放区
touchLeaveVideo() {
if (this.isFirstTouch) return;
if (this.hideTimer) {
clearTimeout(this.hideTimer);
}
// 暂停触摸, 不隐藏
if (this.isPauseTouch) {
this.state.controlBtnShow = true;
this.state.controlBarShow = true;
} else {
this.hideTimer = setTimeout(() => {
this.state.controlBarShow = false;
// 加载中只显示loading
if (this.state.isLoading) {
this.state.controlBtnShow = true;
} else {
this.state.controlBtnShow = false;
}
this.hideTimer = null;
}, 3000);
}
},

视频错误处理和等待处理

这里错误直接用error事件, 加载中用stalled事件来监听视频阻塞状态,等待数据加载用的waiting事件; 显示对应的loading动画即可


// loading动画
@keyframes rotate {
0% {
transform: rotate(0deg);
}
50% {
transform: rotate(180deg);
}
100% {
transform: rotate(360deg);
}
}

.loader {
width: 58px;