flvjs视频流播放组件封装(&断线重连)
发表于:2023-03-06 | 分类: 前端
字数统计: 459 | 阅读时长: 2分钟 | 阅读量:
最近项目中遇到了视频流播放的相关业务处理,因为同时有断线重连的需求,所以为了减少业务页面的代码量,对组件进行封装使用

项目基于 Vue 框架进行开发

  • 上代码
    1
    2
    3
    4
    5
    <template>
    <div class="cameraVideo">
    <video class="videoControl" muted ref="myCameraVideoPlayer"></video>
    </div>
    </template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<script>
export default {
name: "cameraVideo",
props: ["videoData",'autoPlay'],
watch: {},
methods: {
loadVideo() {
console.log("data alive", this.videoData);
this.player && this.destroy();
// props 中的 videoData 为视频流url
this.player = flvjs.createPlayer({
type: "flv",
isLive: true,
url: this.videoData,
hasAudio: false,
hasVideo: true,
cors: true, // 是否跨域
});
this.player.attachMediaElement(this.$refs.myCameraVideoPlayer);
this.player.load();
this.bindEvents();
this.startVideo();
},
bindEvents() {
//视频出错后销毁重新创建
console.log(flvjs);
this.player.on(flvjs.Events.ERROR, this.handleErr);
// this.player.on("loading_complete", this.handleErr);
this.player.on(flvjs.Events.LOADING_COMPLETE, this.handleErr);
// this.player.on(flvjs.Events.RECOVERED_EARLY_EOF, this.handleErr);
// this.player.on("media_info", this.destroy);
// this.player.on("metadata_arrived", this.destroy);
},
handleErr() {
// console.log("errorType:", errorType);
// console.log("errorDetail:", errorDetail);
// console.log("errorInfo:", errorInfo);
if (this.player) {
this.player.pause();
this.player.unload();
this.player.detachMediaElement();
this.player.destroy();
this.player = null;
this.loadVideo();
}
},
startVideo() {
if (this.player) {
this.player.play();
}
},
pause() {
this.player && this.player.pause();
},
destroy() {
if (this.player) {
this.player.pause();
this.player.unload();
this.player.detachMediaElement();
this.player.destroy();
this.player = null;
}
},
},
data() {
return {
supported: false,
player: null,
};
},
mounted() {
// console.log(this.videoData, 2);\
this.player = null;
this.supported = flvjs.isSupported();
// 因为业务需求,封装时autoPlay 的含义为:true 引用组件了即刻加载视频; false 则可以后续refs使用子组件方法load加载播放视频
if(this.autoPlay){
this.loadVideo();
}
},
beforeDestroy() {
console.log("beforeDestroy");
this.destroy();
},
};
</script>
1
2
3
4
5
6
7
8
9
10
<style lang="less" scoped>
.cameraVideo{
position: relative;
.videoControl{
position: absolute;
height: 100%;
width: 100%;
}
}
</style>
上一篇:
Cesium基本地图组件创建
下一篇:
flex布局space-between最后一行展示问题