1.需求概览
需要在管理后台查看直播历史视频,历史视频为hls流视频,格式为http://xxxxxxxx.m3u8
2.界面展示原型
2.封装hls组件
<template>
<video :id="hlsVideoId" :width="dpi[0]" :height="dpi[1]" :autoplay="autoplay" controls></video>
</template>
<script>
export default {
name: "HlsVideo",
props: {
url: {
type: String,
src: ""
},
dpi: {
type: Array,
default: [400, 300]
},
autoplay: {
type: Boolean,
default: false
}
},
data() {
return {
hlsVideo: '',
hlsVideoId: null
};
},
methods: {
// 随机ID
generateRandomString() {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < 8; ++i) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result + Date.now();
},
// 初始化
initHlsVideo() {
// 采用cdn index.html引入 https://cdn.jsdelivr.net/npm/hls.js@latest"
if (Hls.isSupported()) {
let hlsVideoDom = document.getElementById(this.hlsVideoId);
this.hlsVideo = new Hls()
this.hlsVideo.attachMedia(hlsVideoDom)
this.hlsVideo.on(Hls.Events.MEDIA_ATTACHED, () => {
// 每次调用接口列表都要重新创建实例每个视频源不同的实例,所以在父组件使子组件强制刷新渲染(更改组件key)
console.log('创建成功',);
this.hlsVideo.loadSource(this.url);
// 链接错误恢复
if (data.fatal) {
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
// try to recover network error
console.log('fatal network error encountered, try to recover');
hls.startLoad();
break;
case Hls.ErrorTypes.MEDIA_ERROR:
console.log('fatal media error encountered, try to recover');
hls.recoverMediaError();
break;
default:
// cannot recover
hls.destroy();
break;
}
}
})
}
}
},
created() {
// 生成domId
this.hlsVideoId = this.generateRandomString()
},
beforeDestroy() {
//销毁组件实例
this.hlsVideo.destroy()
},
mounted() {
this.initHlsVideo();
}
};
</script>
<style scoped lang="scss"></style>
3.父组件引用table表格
import HlsVideo from '@/views/public/HlsVideo.vue'
<el-table-column label="通话视频" width="220">
<template slot-scope="scope">
<!-- 更改key强制渲染 -->
<HlsVideo :url="scope.row.url" :dpi="[200, 150]" :key="scope.row.url"></HlsVideo>
</template>
</el-table-column>
4.踩坑汇总
1.查询调取改变接口列表数据,导致播放的视频未变化?文章来源:https://www.toymoban.com/news/detail-763650.html
检查发现不同页面还是重复的hls组件实例,使每个页面的hls组件实例唯一性,不复用,给组件绑定key解决文章来源地址https://www.toymoban.com/news/detail-763650.html
到了这里,关于vue+hls.js播放hls视频,踩坑记录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!