起因: 需要动态切换FLV视频流,但是换了地址后,视频无法播放,使用的代码如下。(一些其他类型也可以通过下面方法解决问题)
//重置video的src
this.player.src(url);
//使video重新加载
this.player.load();
框架等: vue + video.js + videojs-flvjs-es6
解决方案: 切换地址的时候,将播放器的dom删除,然后添加新的dom,在重新初始化播放器就可以了。
代码:
HTML
<template>
<div ref="videoPlayerBox" class="component">
<video class="videoPlayer video-js"></video>
</div>
</template>
JS 部分代码
// 初始化播放器
initPlayer () {
this.$nextTick(() => {
let playerOption = {
preload: 'auto', // 预加载
autoplay: true, // 自动播放
controls: true,
techOrder: ['html5', 'flvjs'],
flvjs: {
mediaDataSource: {
cors: true,
withCredentials: false,
},
},
sources: [
{
src: this.streamURL,
type: this.getType(this.streamType) // 这里是自己写的方法,因为要切换多种流,所以不用在意
}
],
}
// this.$el.querySelector('.videoPlayer') 这里也可以用其他的方法传递播放器要绑定的dom节点
this.player = videojs(this.$el.querySelector('.videoPlayer'), playerOption, function onPlayerReady () {
console.log('onPlayerReady', this)
})
})
},
// 重新加载播放器
loadPlayer () {
// 重新创建播放器绑定dom
this.$refs.videoPlayerBox.innerHTML = `<video class="videoPlayer video-js"></video>`
this.$nextTick(() => {
// 重新初始化播放器
this.initPlayer()
})
},