需要完成的效果是:点击树状图然后打开相应的视频,可以指定窗口切换,并在此基础上实现视频播放、关闭视频、开启声音、关闭声音、分屏以及云台操作(包括左右移动、上下移动以及缩放)
使用的海康web插件:由海康官网下载的H5视频播放器开发包 V2.1.2,解压完毕后目录如下:
第一步:引入必要的文件
在public下面创建文件夹,文件名称可以自己起名字,我这里的是lib下面的js,然后把demo文件下的这些文件复制到所创建的文件夹下,最后在public/index.html引入所需要的文件
引入:
<script src="<%= BASE_URL %>lib/js/h5player.min.js" charset="utf-8"></script>
然后在views下面创建一个vue文件:
父组件:
<template>
<div>
<div style="display: flex;">
<el-tree
style="width: 500px;height: 1280px;overflow: auto;"
:data="treeDataList"
:props="defaultProps"
node-key="id" ref="tree"
:default-checked-keys="checkedKeys"
:render-content="renderContent"
@node-click="handleNodeClick"></el-tree>
<div>
<div ref="video">
<video-player class="plyer" ref="player" :option="videoOption" :playback="playback" style="margin-left: 50px;" @getCurrentIndex = "getCurrentIndex">
</video-player>
</div>
<div style="margin-left: 50px;margin-top: 10px;">
<el-tooltip class="item" effect="dark" content="一分屏" placement="top-end">
<img src="xxx/video/splitOne.png" alt="一分屏" @click="screenCut(1)">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="四分屏" placement="top-end">
<img src="xxx/video/splitFour.png" alt="四分屏" @click="screenCut(2)">
</el-tooltip>
<!-- <el-tooltip class="item" effect="dark" content="九分屏" placement="top-end">
<img src="xxx/video/splitNine.png" alt="九分屏" @click="screenCut(3)">
</el-tooltip> -->
<el-tooltip class="item" effect="dark" content="暂停播放" placement="top-end">
<img src="xxx/video/stop.png" alt="暂停移动" @click="stopPlays()">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="开启声音" placement="top-end">
<img v-show="showSound" src="xxx/video/openSound.png" alt="开启声音" @click="openSound()">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="关闭声音" placement="top-end">
<img v-show="!showSound" src="xxx/video/closeSound.png" alt="关闭声音" @click="closeSound()">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="云台" placement="top-end">
<img src="xxx/video/move.png" alt="云台" @click="show()">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="向左移动" placement="top-end">
<img v-show="showOperate" src="xxx/video/left.png" alt="向左移动" @click="control('left')">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="向右移动" placement="top-end">
<img v-show="showOperate" src="xxx/video/right.png" alt="向右移动" @click="control('right')">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="向上移动" placement="top-end">
<img v-show="showOperate" src="xxx/video/up.png" alt="向上移动" @click="control('up')">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="向下移动" placement="top-end">
<img v-show="showOperate" src="xxx/video/down.png" alt="向下移动" @click="control('down')">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="放大" placement="top-end">
<img v-show="showOperate" src="xxx/video/big.png" alt="放大" @click="control('zoom_in')">
</el-tooltip>
<el-tooltip class="item" effect="dark" content="缩小" placement="top-end">
<img v-show="showOperate" src="xxx/video/small.png" alt="缩小" @click="control('zoom_out')">
</el-tooltip>
</div>
</div>
</div>
</div>
</template>
<script>
import VideoPlayer from "./videoPlayer";
import {randomLenNum} from "@/util/util"
export default {
components: {
VideoPlayer
},
data() {
return {
playback: {
startTime: '2021-07-26T00:00:00',
endTime: '2021-07-26T23:59:59',
// valueFormat: moment.HTML5_FMT.DATETIME_LOCAL_SECONDS,
seekStart: '2021-07-26T12:00:00',
rate: ''
},
videoOption:{
width:"2200px",//窗口的宽度
height:"1280px",//窗口的高度
split:2,//2*2 四个屏幕
id:randomLenNum(6)
},
treeDataList: [],
defaultProps: {
children: 'children',
label: 'label'
},
cutnum: 2,
showOperate: false,
currentIndex: 0,
cameraIdList: [],
cameraIdData: [],
currentCameraId: "",
showSound: true
}
},
mounted() {
setTimeout(() => {
this.$refs.player.createPlayer(this.videoOption);
this.loadParentTree();
},0);
//关闭页面的时候销毁以防页面关闭了还会有声音
this.$once('hook:beforeDestroy', () => {
this.closeSound()
})
},
methods:{
show(){//显示云台里面的上下左右操作按钮
this.showOperate = !this.showOperate
},
/* 控制方向 */
control(type) {
//拿到当前选中窗口id
this.currentCameraId = this.cameraIdList[this.currentIndex].cameraId
this.$axios.get("xxx?id=" + this.currentCameraId + '&command=' + type)
.then(() => {})
},
/* 分屏 */
screenCut(num) {
this.cutnum = num
this.videoOption.split = num
setTimeout(()=>{
this.$refs.player.arrangeWindow(num)
},500)
},
/* 暂停播放 */
stopPlays() {
this.$refs.player.stopPlay(this.currentIndex);
},
//获取当前选中窗口的索引
getCurrentIndex(index) {
this.currentIndex = index
if(this.cameraIdList.length - 1 > index) {
this.currentCameraId = this.cameraIdList[this.currentIndex].cameraId
}
},
/* 开启声音 */
openSound() {
this.showSound = !this.showSound
this.$refs.player.openSound(this.currentIndex);
},
/* 关闭声音 */
closeSound() {
this.showSound = !this.showSound
this.$refs.player.closeSound(this.currentIndex);
},
loadParentTree(){
this.cameraIdData = []
for(let i =0;i < 9;i++) {
this.cameraIdData.push({
stream: "",
cameraId: ""
})
}
this.$axios.get("xxx/tree").then(res=>{
const data = res.data.data;
this.treeDataList = data
// 默认加载第一个
this.$axios.get("xxxgetliu?type=" + this.treeDataList[0].type + "&id=" + this.treeDataList[0].id + "&ping=" + this.cutnum*this.cutnum).then(res=>{
const dataList=res.data.data;
this.dataProcess(dataList)
this.cameraIdList = dataList
})
})
},
handleNodeClick(data,node,b) {
if(data.type == "parent") {//如果当前点击的是父级的话,默认加载当前分屏的数量
this.$axios.get("xxx/getliu?type=" + data.type + "&id=" + data.id + "&ping=" + this.cutnum*this.cutnum).then(res=>{
const dataList=res.data.data;
this.dataProcess(dataList)
this.cameraIdList = dataList
})
} else if(data.type == "child") {//当前点击的是子级
this.$axios.get("xxx/getliu?type=" + data.type + "&id=" + data.id + "&ping=" + this.cutnum*this.cutnum).then(async res=>{
const dataList=res.data.data;
await this.loadVideo(dataList[0].stream,this.currentIndex);
for(let i =0;i < this.cameraIdData.length ;i++) {
for(let j =0;j < this.cameraIdList.length ;j++) {
if(i == j) {
this.cameraIdData[i].stream = this.cameraIdList[j].stream
this.cameraIdData[i].cameraId = this.cameraIdList[j].cameraId
}
}
}
this.cameraIdData[this.currentIndex].stream = dataList[0].stream
this.cameraIdData[this.currentIndex].cameraId = dataList[0].cameraId
})
}
},
async dataProcess(arr,type) {
for(let i = 0; i < arr.length; i++){
await this.loadVideo(arr[i].stream,i,type);
}
},
loadVideo(liuName,index,type){
let param = {
url: liuName,
index: index
}
this.$refs.player.play(param);
},
renderContent(h, { node, data, store }) {
return (
<span class="custom-tree-node">
<span>{data.label}</span>
<span>{data.count ? '(' + data.count + ')' : ''}</span>
</span>);
}
}
}
</script>
<style lang="scss" scoped>
::v-deep .el-tree-node:focus>.el-tree-node__content {
background-color: transparent !important;
}
::v-deep .el-tree {
background: transparent !important;
color: #fff;
}
::v-deep .el-tree-node>.el-tree-node__children{
background-color: transparent;
}
::v-deep .el-tree-node__label {
font-size: 30px;
height: auto;
line-height: 60px;
}
::v-deep .el-tree-node,
::v-deep .el-tree-node__content {
height: auto;
line-height: 60px;
align-items: flex-start;
}
::v-deep .el-tree-node__expand-icon {
font-size: 40px;
}
::v-deep .el-tree-node__content:hover,
::v-deep .el-upload-list__item:hover,
::v-deep .el-tree-node.is-current>.el-tree-node__content {
background-color: transparent;
}
::v-deep .custom-tree-node{
font-size: 30px;
}
img {
display: inline-block;
width: 40px;
height: 40px;
margin: 0 20px;
cursor: pointer;
}
::v-deep [class^=el-icon-]{
font-size: 40px;
color: #fff;
margin: 0 20px;
cursor: pointer;
}
</style>
子组件:
<template>
<!-- <el-container>
<el-row>
<el-input v-model="code" placeholder="输入监控点编码" @change="onChangeCode"></el-input>
<el-button @click="onSubmit">默认预览</el-button>
<el-button @click="onTwoSubmit(2)">4分屏</el-button>
<el-button @click="onTwoSubmit(4)">16分屏</el-button>
<el-button @click="onTwoSubmit(8)">64分屏</el-button>
</el-row>
<el-row>
<div id="player" style="width: 800px;height: 800px;"></div>
</el-row>
</el-container> -->
<div :id="`player${option.id}`"></div>
</template>
<script>
export default {
name:"VideoPlayer",
props:{
option: {
id: {
type: String,
default: ""
},
url:{
type: String,
default: ''
},
beginTime:{
type: String,
default: ''
},
endTime:{
type: String,
default: ''
},
width:{
type: String,
default: '784px'
},
height:{
type: String,
default: '440px'
},
split:{
type:Number,
default:1
},
index:{
type:Number,
default:0
},
},
playback: {
startTime:{
type: String,
default: ''
},
endTime:{
type: String,
default: ''
},
seekStart:{
type: String,
default: ''
},
rate: {
type: String,
default: ''
}
}
},
data() {
return {
player: null,
count: 0
}
},
mounted() {
this.$nextTick(() => {
this.$el.style.setProperty('display', 'block');
this.$el.style.setProperty('width', this.option.width||"784px");
this.$el.style.setProperty('height', this.option.height||"440px");
// this.initPlayer(this.option);
// this.play(this.option);
});
},
// watch:{
// option(){
// if(this.option){
// this.play(this.option);
// }
// }
// },
methods: {
initPlayer(option) {
// 设置播放容器的宽高并监听窗口大小变化
window.addEventListener('resize', () => {
this.player.JS_Resize()
})
this.player = new window.JSPlugin({
// 需要英文字母开头 必填,
szId: 'player'+option.id,
// 必填,引用H5player.min.js的js相对路径
szBasePath: '../../../../lib/js',
// 当容器div#play_window有固定宽高时,可不传iWidth和iHeight,窗口大小将自适应容器宽高
// iWidth: 600,
// iHeight: 400,
// 分屏播放,默认最大分屏4*4
iMaxSplit: 4,
iCurrentSplit: option.split,
openDebug:false,
// 样式
oStyle: {
border: '#343434',
borderSelect: '#FFCC00',
background: '#000'
}
});
},
play(option,callback) {
return new Promise((resolve) => {
const param = {
playURL: option.url,
mode: 1
}
let index = option.index;
if(option.beginTime&&option.endTime) {
this.player.JS_Play(option.url, param, index,option.beginTime,option.endTime).then(() => {
// 播放成功回调
resolve(true);
},
(err) => {
resolve(false);
console.log('播放失败')
});
} else {
this.player.JS_Play(option.url,param,index).then(() => {
resolve(true);
},(err) => {
resolve(false);
console.log("play fail");
})
}
})
/* console.log(option);
const _this = this;
const param = { playURL: option.url,mode: 1};
var index=option.index||0;
// if (!index) {
// index = 0
// }
if(option.beginTime&&option.endTime){
_this.player.JS_Play(option.url, param, index,option.beginTime,option.endTime).then(() => {
// 播放成功回调
},
(err) => {
console.log('播放失败')
});
}else{
_this.player.JS_Play(option.url, param, index).then(() => {
// 播放成功回调
},
(err) => {
console.log('播放失败')
});
} */
},
init() {
// 设置播放容器的宽高并监听窗口大小变化
window.addEventListener('resize', () => {
setTimeout(()=>{
this.player.JS_Resize()
},50)
})
},
reSize(){
this.player.JS_Resize()
},
/* getTraceId(curIndex){
return new Promise((resolve) => {
this.player.JS_GetTraceId(curIndex).then((traceId) => {
console.log(this.player,traceId,"185");
resolve(traceId);
},(err) => {
console.log(err);
})
})
}, */
createPlayer(option) {
this.player = new window.JSPlugin({
szId: 'player'+option.id,
szBasePath: '../../../../lib/js',
iMaxSplit: 4,
iCurrentSplit: option.split,
openDebug: false,
oStyle: {
border: '#343434',
borderSelect: '#FFCC00',
background: '#000'
}
});
// 事件回调绑定
this.player.JS_SetWindowControlCallback({
windowEventSelect: async (iWndIndex)=> { //插件选中窗口回调
console.log(iWndIndex);
// let traceId = await this.getTraceId(iWndIndex);
// console.log(traceId,"traceId");
this.$emit("getCurrentIndex", iWndIndex);
},
pluginErrorHandler: (iWndIndex, iErrorCode, oError)=> { //插件错误回调
console.log('pluginError callback: ', iWndIndex, iErrorCode, oError);
if(iErrorCode == "0x12f910012" || iErrorCode == "0x01900050" || iErrorCode == "0x01b01307") {
this.$message.warning("窗口取流失败,详情根据错误码在运管后台进行查询.")
} else if(iErrorCode == "0x12f910011") {
this.$message.warning("流中断,电脑配置过低,程序卡主线程都可能导致流中断")
} else if(iErrorCode == "0x12f910010") {
this.$message.warnng("取流失败")
}
},
windowEventOver: (iWndIndex)=> { //鼠标移过回调
//console.log(iWndIndex);
},
windowEventOut: (iWndIndex)=> { //鼠标移出回调
//console.log(iWndIndex);
},
windowEventUp: (iWndIndex)=> { //鼠标mouseup事件回调
//console.log(iWndIndex);
},
windowFullCcreenChange: (bFull)=> { //全屏切换回调
console.log('fullScreen callback: ', bFull);
},
firstFrameDisplay: (iWndIndex, iWidth, iHeight)=> { //首帧显示回调
console.log('firstFrame loaded callback: ', iWndIndex, iWidth, iHeight);
},
performanceLack: ()=> { //性能不足回调
console.log('performanceLack callback: ');
},
StreamEnd: (index)=> { //回放结束回调,返回对应测窗口id
this.option.index=index;
this.play(this.option);
}
});
},
/* 分屏 */
arrangeWindow(splitNum) {
// let splitNum = this.splitNum 1
this.player.JS_ArrangeWindow(splitNum).then(
() => {
console.log(`arrangeWindow to ${splitNum}x${splitNum} success`)
},
e => { console.error(e) }
);
},
selectWindow(index){
this.player.JS_SelectWnd(index).then(
() => { },
e => { console.error(e) }
);
},
/* 整体全屏 */
wholeFullScreen(boolean) {
this.init();
this.player.JS_FullScreenDisplay(boolean).then(
() => { console.log(`wholeFullScreen success`) },
e => { console.error(e) }
);
},
/* 单窗口全屏 */
singleFullScreen(index) {
this.player.JS_FullScreenSingle(index).then(
() => {
console.info('JS_FullScreenSingle success');
// do you want...
},
(err) => {
console.info(err);
// do you want...
}
);
},
/* 预览&对讲 */
realplay() {
let { player, mode, urls } = this,
index = player.currentWindowIndex,
playURL = urls.realplay;
player.JS_Play(playURL, { playURL, mode }, index).then(
() => { console.log('realplay success') },
e => { console.error(e) }
);
},
/* 停止播放 */
stopPlay(index) {
console.log("当前选中要暂停的视频是:" + index );
this.player.JS_Stop(index).then(
() => { this.playback.rate = 0; console.log('stop realplay success') },
e => { console.error(e) }
);
},
/* 开始对讲 */
talkStart(url) {
console.log(url);
// let url = this.urls.talk
this.player.JS_SetConnectTimeOut(0, 1000);
this.player.JS_StartTalk(url).then(
() => { console.log('talkStart success') },
e => { console.error(e) }
);
},
/* 停止对讲 */
talkStop() {
this.player.JS_StopTalk().then(
() => { console.log('talkStop success') },
e => { console.error(e) }
);
},
/* 停止所有播放 */
stopAllPlay() {
this.player.JS_StopRealPlayAll().then(
() => { this.playback.rate = 0; console.log('stopAllPlay success') },
e => { console.error(e) }
);
},
/* 回放 */
playbackStart() {
let { player, mode, urls, playback } = this,
index = player.currentWindowIndex,
playURL = urls.playback,
{ startTime, endTime } = playback
startTime += 'Z'
endTime += 'Z'
player.JS_Play(playURL, { playURL, mode }, index, startTime, endTime).then(
() => {
console.log('playbackStart success')
this.playback.rate = 1
},
e => { console.error(e) }
);
},
/* 暂停回放 */
playbackPause() {
this.player.JS_Pause().then(
() => { console.log('playbackPause success') },
e => { console.error(e) }
)
},
/* 恢复回放 */
playbackResume() {
this.player.JS_Resume().then(
() => { console.log('playbackResume success') },
e => { console.error(e) }
)
},
/* 回放定位 */
seekTo() {
let { seekStart, endTime } = this.playback
seekStart += 'Z'
endTime += 'Z'
this.player.JS_Seek(this.player.currentWindowIndex, seekStart, endTime).then(
() => { console.log('seekTo success') },
e => { console.error(e) }
)
},
/* 回放慢放 */
playbackSlow() {
this.player.JS_Slow().then(
rate => {
this.playback.rate = rate
},
e => { console.error(e) }
)
},
/* 回放快放 */
playbackFast() {
this.player.JS_Fast().then(
rate => {
this.playback.rate = rate
},
e => { console.error(e) }
)
},
/* 回放单帧进(高级模式功能) */
frameForward() {
this.player.JS_FrameForward(this.player.currentWindowIndex).then(
() => { this.playback.rate = 1; console.log('frameForward success') },
e => { console.error(e) }
)
},
/* 开启声音 */
openSound(index) {
this.player.JS_OpenSound(index).then(
() => {
console.log('openSound success')
this.muted = false
},
e => { console.error(e) }
)
},
/* 关闭声音 */
closeSound(index) {
this.player.JS_CloseSound(index).then(
() => {
console.log('closeSound success')
this.muted = true
},
e => { console.error(e) }
)
},
/* 设置音量 */
setVolume(value) {
let player = this.player,
index = player.currentWindowIndex
this.player.JS_SetVolume(index, value).then(
() => {
console.log('setVolume success', value)
},
e => { console.error(e) }
)
},
/* 抓图 */
capture(imageType) {
let player = this.player,
index = player.currentWindowIndex
player.JS_CapturePicture(index, 'img', imageType).then(
() => { console.log('capture success', imageType) },
e => { console.error(e) }
)
},
/* 录像 */
recordStart(type) {
const codeMap = { MP4: 5, PS: 2 }
let player = this.player,
index = player.currentWindowIndex,
fileName = `${moment().format('YYYYMMDDHHmm')}.mp4`
typeCode = codeMap[type]
player.JS_StartSaveEx(index, fileName, typeCode).then(
() => { console.log('record start ...') },
e => { console.error(e) }
)
},
/* 停止录像并保存文件 */
recordStop() {
let player = this.player
index = player.currentWindowIndex
player.JS_StopSave(index).then(
() => { console.log('record stoped, saving ...') },
e => { console.error(e) }
)
},
/* 电子放大、智能信息 */
enlarge() {
let player = this.player,
index = player.currentWindowIndex
player.JS_EnableZoom(index).then(
() => { console.log('enlarge start..., select range...') },
e => { console.error(e) }
)
},
enlargeClose() {
let player = this.player,
index = player.currentWindowIndex
player.JS_DisableZoom(index).then(
() => { console.log('enlargeClose success') },
e => { console.error(e) }
)
},
/* 开启/关闭智能信息展示(高级模式功能) */
intellectTrigger(openFlag) {
let player = this.player,
index = player.currentWindowIndex
let result = player.JS_RenderALLPrivateData(index,openFlag)
console.log(`${openFlag ? 'open' : 'close'} intellect ${result === 1 ? 'success': 'failed'}`)
},
/* 获取音视频信息 */
getvideoInfo() {
let player = this.player,
index = player.currentWindowIndex
player.JS_GetVideoInfo(index).then(function (videoInfo) {
console.log("videoInfo:", videoInfo);
});
},
/* 获取OSD时间 */
getOSDTime() {
let player = this.player,
index = player.currentWindowIndex
player.JS_GetOSDTime(index).then(function(time) {
console.log("osdTime:", new Date(time));
});
},
getCurrentIndex(){
return this.player.currentWindowIndex;
}
},
}
</script>
<style>
</style>
(注:图片可以在阿里图标库查找)
randomLenNum这个自己新建一个js放进去就好了
/**
* 生成随机len位数字
*/
export const randomLenNum = (len, date) => {
let random = '';
random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
if (date) random = random + Date.now();
return random;
};
效果图:
里面播放的内容就不展示了,大致效果就是这个样子了