前段时间遇到新项目需要播放视频和直播(监控格式为flv和吗m3u8,直播格式为flv),踩了很多坑,现记录下来备忘和分享。(目前都已经换成了tcplayer视频播放插件,下一篇介绍)
使用ckplayer (适用于视频和监控的播放,适合一个页面只有一个播放视频)
- 引用ckplayer
下载 ckplayer,将下载文件中ckplayer文件夹移入public文件夹内,在index.html文件中引入ckplayer如下图
- 使用ckplayer
<template>
<div>
<div class="ckplayer video-box">
<div id="video"></div>
</div>
</div>
</template>
<script>
export default {
name: "Ckplayer",
components: {},
data() {
return {
videoObject: {
width: 500, // 宽度,也可以支持百分比(不过父元素宽度要有)
height: 300, // 高度,也可以支持百分比
container: "#video", //“#”代表容器的ID,“.”或“”代表容器的class
variable: "player", //该属性必需设置,值等于下面的new chplayer()的对象
volume: 0, //音量,范围:0-1
// loaded:'loadedHandler',
autoplay: true, //自动播放
flashplayer: false,
html5m3u8: true, //PC平台上是否使用h5播放器播放m3u8
live: true, //是否是直播
unescape: false, //默认flashplayer里需要解码
overspread: true, //是否让视频铺满播放器
video: "" //视频地址(必填)
},
};
},
created() {},
methods: {},
mounted() {
this.videoObject.video = 'http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8';
let player = new ckplayer(this.videoObject);
}
};
</script>
<style lang="scss" scoped>
.video-box {
margin: 0 auto;
width: 500px;
height: 300px;
#video {
width: 100%;
height: 100%;
}
}
</style>
使用flv.js播放直播 (适合格式只有flv格式的直播和视频)
- 安装flv.js
npm install flv.js
- 使用 flv.js
<template>
<div>
<video id="myvideo"></video>
<div class="button" @click="click(1)">切换直播</div>
<div class="button" @click="click(2)">切换直播</div>
<div class="button" @click="click(3)">切换直播</div>
</div>
</template>
<script>
import flvjs from "flv.js";
export default {
name: "Flv",
components: {},
data() {
return {
flvPlayer: null,
// 直播链接数组
liveList: [
"",
"",
""
],
liveUrl: ""
};
},
created() {},
methods: {
click(num) {
if (num == 1) {
if (this.flvPlayer) {
this.pausemix();
}
this.liveUrl = this.liveList[0];
this.createFlvPlayer();
} else if (num == 2) {
if (this.flvPlayer) {
this.pausemix();
}
this.liveUrl = this.liveList[1];
this.createFlvPlayer();
} else {
if (this.flvPlayer) {
this.pausemix();
}
this.liveUrl = this.liveList[1];
this.createFlvPlayer();
}
},
createFlvPlayer() {
let _this = this;
if (flvjs.isSupported()) {
const videoElement = document.getElementById("myvideo");
this.flvPlayer = flvjs.createPlayer({
type: "flv",
isLive: true,
hasAudio: false,
enableWorker: true,
enableStashBuffer: false,
stashInitialSize: 128,
url: _this.liveUrl
});
this.flvPlayer.attachMediaElement(videoElement);
this.flvPlayer.load();
this.flvPlayer.play();
} else {
console.log("not support");
}
},
pausemix() {
this.flvPlayer.pause();
this.flvPlayer.unload();
this.flvPlayer.detachMediaElement();
this.flvPlayer.destroy();
this.flvPlayer = null;
}
},
mounted() {
// this.createFlvPlayer()
},
beforeDestroy() {
this.pausemix();
}
};
</script>
<style lang="scss" scope>
#myvideo {
width: 400px;
height: 200px;
}
.button {
margin: 0 auto;
width: 100px;
height: 50px;
line-height: 50px;
margin-bottom: 10px;
border: 1px solid gray;
cursor: pointer;
}
</style>