Vue中使用flv.js播放flv格式视频流
1.安装依赖
npm install flv.js --save --legacy-peer-deps
2.具体代码
Html部分
<template>
<div>
<video autoplay controls id="myVideoFlv" />
</div>
</template>
JS部分
<script>
import flvjs from 'flv.js/dist/flv.min.js'
export default {
name: "VideoFlv",
data() {
return {
flvPlayer: null,
webrtcUrl: "Your Flv Video URL"
}
},
mounted() {
this.webrtcPlay()
},
beforeDestroy() {
this.destoryVideo()
},
methods: {
webrtcPlay() {
if (flvjs.isSupported()) {
if (this.flvPlayer) {
this.flvPlayer.pause()
this.flvPlayer.unload()
this.flvPlayer.detachMediaElement()
this.flvPlayer.destroy()
}
this.flvPlayer = flvjs.createPlayer(
{
type: 'flv',
url: this.webrtcUrl
},
{
cors: true, //是否跨域
enableWorker: true, //是否多线程工作
anableStashBuffer: false, //是否启用缓存
stashInitialSize: 384, //缓存大小(kb) 默认384kb
autoCleanupSourceBuffer: true //是否自动缓存
}
)
this.flvPlayer.attachMediaElement(document.getElementById('myVideo')) // 在这里绑定元素
this.flvPlayer.load()
this.flvPlayer.play()
//报错重连
this.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
console.log('errType:', errType)
console.log('errorDetail:', errDetail)
if(this.flvPlayer){
this.destoryVideo()
this.webrtcPlay()
}
})
}
},
destoryVideo() {
if (this.flvPlayer) {
this.flvPlayer.pause()
this.flvPlayer.unload()
this.flvPlayer.detachMediaElement()
this.flvPlayer.destroy()
this.flvPlayer = null
}
}
}
}
</script>