海康视频【1.5.4】-vue2实现监控

524 阅读3分钟

引入海康插件

public/index.html

image.png

 <!--  引入海康插件  --> 
 <script type="text/javascript" src="./haikang/jquery-1.12.4.min.js"></script>  
 <script type="text/javascript" src="./haikang/jsencrypt.min.js"></script>  
 <script type="text/javascript" src="./haikang/web-control_1.2.7.min.js"></script>

创建一个HKViedo的组件

HKVideo/HKPlayer.vue
<template>
  <div id="playWnd" class="playWnd" />
</template>
 
<script>
//加密
import JSEncrypt from 'jsencrypt/bin/jsencrypt'
// import { getAllUrlParams } from '@/utils/MtUtil'
 
// 声明公用变量
var oWebControl = null
var oWebControl2 = null
var initCount = 0
var pubKey = ''
export default {
  name: 'VideoPlayer',
  /**
   * index :当前组件所属页面 设备管理 为空 ||实时监控 realTime
   * type : 回放 || 直播
   * code : 监控点编号 监控设备页面String || 实时监控 Array
   * time 回放时间 暂时废弃
   */
  // props: ['mode', 'code'],
  props: {
    // 综合安防管理平台提供的appkey
    code: {
      type: String,
      default: '',
    },
    appkey: {
      type: String,
      default: '25459272',
    },
    // 综合安防管理平台提供的secret
    secret: {
      type: String,
      default: '910KRnyrcDzLYvahH0i3',
    },
    // 综合安防管理平台IP地址
    playIp: {
      type: String,
      default: '10.1.190.1',
    },
    // 综合安防管理平台端口
    port: {
      type: Number,
      default:8443 ,
    },
    // 播放模式
    playMode: {
      type: Number,
      default: 1,
    },
    // 是否显示控件
    showToolbar: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      swfWidth: window.innerWidth - 600,
      swfHeight: window.innerHeight - 240,
      // swfHeight: window.innerHeight - 150,
      playText: '',
      mode: '1', // 0-预览,1-回放
      // code: '5af4de819dd3431faa57b04389c3baa9', // 监控点
    }
  },
  // created(){
  //   this.$rwBus.$on("hideViedo",(()=>{
  //     let _this=this;
  //     _this.handleHide();
  //   }));
  //   this.$rwBus.$on("showViedo",(()=>{
  //     let _this=this;
  //     _this.handleShow();
  //   }));
  // },
  mounted() {
    // let params = getAllUrlParams()
    if (this.$rwBus) {
      this.$rwBus.$on("hideViedo",(()=>{
      let _this=this;
      _this.handleHide();
    }));
    this.$rwBus.$on("showViedo",(()=>{
      let _this=this;
      _this.handleShow();
    }));
    }
    this.mode = '0'
    // this.code = '5af4de819dd3431faa57b04389c3baa9'
    this.initPlugin() // 初始化video界面
    window.addEventListener('resize', this.SetDocOffset)
  },
  destroyed() {
    // 组件销毁后
    this.$rwBus.$off('hideViedo', this.handleHide);
    this.$rwBus.$off('showViedo', this.handleShow);
    this.destoryWnd()
    window.removeEventListener('resize', this.SetDocOffset)
  },
  beforeDestroy() {
    this.destoryWnd()
  },
  methods: {
    // 下载插件
    // frontDownload() {
    //   var a = document.createElement('a') // 创建一个<a></a>标签
    //   a.href = 'https://116.179.49.48:18081' + 'haikang/VideoWebPlugin.exe' // 给a标签的href属性值加上地址,注意,这里是绝对路径,不用加 点.
    //   a.href = process.env.BASE_URL + 'haikang/VideoWebPlugin.exe' // 给a标签的href属性值加上地址,注意,这里是绝对路径,不用加 点.
 
    //   a.download = 'VideoWebPlugin.exe' // 设置下载文件文件名,这里加上.xlsx指定文件类型,pdf文件就指定.fpd即可
    //   a.style.display = 'none' // 障眼法藏起来a标签
    //   document.body.appendChild(a) // 将a标签追加到文档对象中
    //   a.click() // 模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
    //   a.remove() // 一次性的,用完就删除a标签
    // },
    // 创建播放实例
    initPlugin() {
      var that = this
      oWebControl = new window.WebControl({
        szPluginContainer: 'playWnd', // 指定容器id
        iServicePortStart: 15900, // 指定起止端口号,建议使用该值
        iServicePortEnd: 15909,
        szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11', // 用于 IE10 使用 ActiveX 的 clsid
        cbConnectSuccess: function () {
          // 创建WebControl实例成功
          oWebControl
            .JS_StartService('window', {
              // WebControl实例创建成功后需要启动服务
              dllPath: './VideoPluginConnect.dll', // 值"./VideoPluginConnect.dll"写死
            })
            .then(
              function () {
                // 启动插件服务成功
                oWebControl.JS_SetWindowControlCallback({
                  // 设置消息回调
                  cbIntegrationCallBack: that.cbIntegrationCallBack,
                })
 
                oWebControl
                  .JS_CreateWnd('playWnd', that.swfWidth, that.swfHeight)
                  .then(function () {
                    // JS_CreateWnd创建视频播放窗口,宽高可设定
                    that.init() // 创建播放实例成功后初始化
                  })
              },
              function () {
                // 启动插件服务失败
              },
            )
        },
        cbConnectError: function () {
          // 创建WebControl实例失败
          oWebControl = null
          that.$message.warning('插件未启动,正在尝试启动,请稍候...')
          that.playText = '插件未启动,正在尝试启动,请稍候...'
          // that.frontDownload()
          // document.querySelector('#playWnd').innerHTML('插件未启动,正在尝试启动,请稍候...')
          // $('#playWnd').html('插件未启动,正在尝试启动,请稍候...')
          window.WebControl.JS_WakeUp('VideoWebPlugin://') // 程序未启动时执行error函数,采用wakeup来启动程序
          initCount++
          if (initCount < 3) {
            setTimeout(function () {
              that.initPlugin()
            }, 3000)
          } else {
            that.$message.warning('插件启动失败,请检查插件是否安装!')
            // console.log(initCount)
            that.playText = '插件启动失败,请检查插件是否安装!'
            if (initCount == 3) {
              that.frontDownload()
            }
            // document.querySelector('#playWnd').innerHTML('插件启动失败,请检查插件是否安装!')
            // $('#playWnd').html('插件启动失败,请检查插件是否安装!')
          }
        },
        cbConnectClose: () => {
          // 异常断开:bNormalClose = false
          // JS_Disconnect正常断开:bNormalClose = true
          console.log('cbConnectClose')
          oWebControl = null
        },
      })
      this.oWebControl2 = oWebControl;
    },
    init() {
      const that = this
      this.getPubKey(() => {
        //  请自行修改以下变量值
        let appkey = that.appkey // 综合安防管理平台提供的appkey,必填
        let secret = that.setEncrypt(that.secret) // 综合安防管理平台提供的secret,必填
        let ip = that.playIp // 综合安防管理平台IP地址,必填
        let playMode = 0// 初始播放模式:0-预览,1-回放
        let port = that.port // 综合安防管理平台端口,若启用HTTPS协议,默认443
        let snapDir = 'D:\\SnapDir' // 抓图存储路径
        let videoDir = 'D:\\VideoDir' // 紧急录像或录像剪辑存储路径
        let layout = '1x1' // playMode指定模式的布局
        let enableHTTPS = 1 // 是否启用HTTPS协议与综合安防管理平台交互,这里总是填1
        let encryptedFields = 'secret' // 加密字段,默认加密领域为secret
        let showToolbar = 1 // 是否显示工具栏,0-不显示,非0-显示
        let showSmart = 1 // 是否显示智能信息(如配置移动侦测后画面上的线框),0-不显示,非0-显示
        let buttonIDs = '0,16,257,259,516,768,769' // 自定义工具条按钮
        //  
 
        oWebControl
          .JS_RequestInterface({
            funcName: 'init',
            argument: JSON.stringify({
              appkey: appkey, // API网关提供的appkey
              secret: secret, // API网关提供的secret
              ip: ip, // API网关IP地址
              playMode: playMode, // 播放模式(决定显示预览还是回放界面)
              port: port, // 端口
              snapDir: snapDir, // 抓图存储路径
              videoDir: videoDir, // 紧急录像或录像剪辑存储路径
              layout: layout, // 布局
              enableHTTPS: enableHTTPS, // 是否启用HTTPS协议
              encryptedFields: encryptedFields, // 加密字段
              showToolbar: showToolbar, // 是否显示工具栏
              showSmart: showSmart, // 是否显示智能信息
              buttonIDs: buttonIDs, // 自定义工具条按钮
            }),
          })
          .then(function (oData) {
            oWebControl.JS_Resize(that.swfWidth, that.swfHeight) // 初始化后resize一次,规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
            if (that.mode == 0) {
              that.startPreview(that.code)
            } else {
              that.startPlayback(that.code)
            }
            that.playText = ''
          })
      })
    },
    // 获取公钥
    getPubKey(callback) {
      oWebControl
        .JS_RequestInterface({
          funcName: 'getRSAPubKey',
          argument: JSON.stringify({
            keyLength: 1024,
          }),
        })
        .then(function (oData) {
          if (oData.responseMsg.data) {
            pubKey = oData.responseMsg.data
            callback()
          }
        })
    },
    // RSA加密
    setEncrypt(value) {
      var encrypt = new JSEncrypt()
      encrypt.setPublicKey(pubKey)
      return encrypt.encrypt(value)
    },
    // 回调的消息
    cbIntegrationCallBack(oData) {
      const { responseMsg: type, responseMsg: msg } = oData
 
      if (type === 'error') {
        //TODO: 先注释
        // console.log(
        //   type,
        //   msg,
        //   this.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        // )
      } else {
        // console.log(
        //   type,
        //   msg,
        //   this.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        // )
      }
    },
    // 预览
    startPreview(cameraCode) {
      // 点击查询后显示
      oWebControl.JS_ShowWnd()
      var cameraIndexCode = cameraCode // 获取输入的监控点编号值,必填
      var streamMode = 0 // 主子码流标识:0-主码流,1-子码流
      var transMode = 1 // 传输协议:0-UDP,1-TCP
      var gpuMode = 0 // 是否启用GPU硬解,0-不启用,1-启用
      var wndId = -1 // 播放窗口序号(在2x2以上布局下可指定播放窗口)
 
      cameraIndexCode = cameraIndexCode.replace(/(^\s*)/g, '')
 
      oWebControl.JS_RequestInterface({
        funcName: 'startPreview',
        argument: JSON.stringify({
          cameraIndexCode: cameraIndexCode, // 监控点编号
          streamMode: streamMode, // 主子码流标识
          transMode: transMode, // 传输协议
          gpuMode: gpuMode, // 是否开启GPU硬解
          wndId: wndId, // 可指定播放窗口
        }),
      })
    },
    // 停止全部预览
    stopAllPreview() {
      oWebControl.JS_RequestInterface({
        funcName: 'stopAllPreview',
      })
    },
    // 回放
    startPlayback(cameraCode) {
      let cameraIndexCode = cameraCode // 获取输入的监控点编号值,必填
      // let startTimeStamp = new Date().getTime() - 24 * 60 * 60 * 1000 // 回放开始时间戳,必填
      // let endTimeStamp = new Date().getTime() // 回放结束时间戳,必填
      // let startTimeStamp = new Date(this.startTime.replace('-', '/').replace('-', '/')).getTime() // 回放开始时间戳,必填
      // let endTimeStamp = new Date(this.endTime.replace('-', '/').replace('-', '/')).getTime() // 回放结束时间戳,必填
      let recordLocation = 0 // 录像存储位置:0-中心存储,1-设备存储
      let transMode = 1 // 传输协议:0-UDP,1-TCP
      let gpuMode = 0 // 是否启用GPU硬解,0-不启用,1-启用
      let wndId = -1 // 播放窗口序号(在2x2以上布局下可指定播放窗口)
 
      oWebControl.JS_RequestInterface({
        funcName: 'startPlayback',
        argument: {
          cameraIndexCode: cameraIndexCode, // 监控点编号
          // startTimeStamp: Math.floor(startTimeStamp / 1000).toString(), // 录像查询开始时间戳,单位:秒
          // endTimeStamp: Math.floor(endTimeStamp / 1000).toString(), // 录像结束开始时间戳,单位:秒
          recordLocation: recordLocation, // 录像存储类型:0-中心存储,1-设备存储
          transMode: transMode, // 传输协议:0-UDP,1-TCP
          gpuMode: gpuMode, // 是否启用GPU硬解,0-不启用,1-启用
          wndId: wndId, // 可指定播放窗口
        },
      })
    },
    // 停止全部回放
    stopAllPlayback() {
      oWebControl.JS_RequestInterface({
        funcName: 'stopAllPlayback',
      })
    },
    // 调整插件窗口大小、位置接
    SetDocOffset() {
      if (oWebControl != null) {
        oWebControl.JS_Resize(this.swfWidth, this.swfHeight)
      }
    },
    // 插件窗口销毁
    destoryWnd() {
      if (oWebControl != null) {
        oWebControl.JS_HideWnd() // 先让窗口隐藏,规避可能的插件窗口滞后于浏览器消失问题
        oWebControl.JS_RequestInterface({
          funcName: 'destroyWnd',
        }) // 销毁当前播放的视频
        oWebControl.JS_Disconnect() // 断开与插件服务连接
      }
    },
 
    // 格式化时间
    dateFormat(oDate, fmt) {
      var o = {
        'M+': oDate.getMonth() + 1, // 月份
        'd+': oDate.getDate(), // 日
        'h+': oDate.getHours(), // 小时
        'm+': oDate.getMinutes(), // 分
        's+': oDate.getSeconds(), // 秒
        'q+': Math.floor((oDate.getMonth() + 3) / 3), // 季度
        S: oDate.getMilliseconds(), // 毫秒
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (oDate.getFullYear() + '').substr(4 - RegExp.$1.length),
        )
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length),
          )
        }
      }
      return fmt
    },
    // 隐藏视频
    handleHide() {
      console.log('调用隐藏接口',oWebControl)
      //隐藏视频插件,解决遮挡弹窗问题
      if (oWebControl) {
        console.log('00000000000000000000')
        oWebControl.JS_HideWnd();
      }
    },
    // 显示视频
    handleShow() {
    // 显示视频插件
    console.log('调用显示接口',oWebControl)
      if (oWebControl) {
        console.log('11111111')

        oWebControl.JS_ShowWnd();
      }
    },

  },
}
</script>
 
<style lang="scss" scoped>
.playWnd {
  width: 100%;
  height: 100%;
  margin-top: 85px;
}
</style>

解决播放时覆盖其他弹框问题

handleHide()handleShow  可以通过bus.on和bus.$emit来调用显示和隐藏

页面使用

<HKPlayer style="width: 88%;" :code="cameraIndexCode" ref="videoRef"></HKPlayer>

import HKPlayer from "@/HKVideo/HKPlayer.vue";
export default {  components: {    HKPlayer  },
  data(){
       cameraIndexCode: '', //视频播放code   
   }   
   watch: {    
       cameraIndexCode:{      
           handler(value){        
               this.$refs.videoRef.startPreview(value)      
           }    
       }
   }
}

文档

工具条分为上下两个工具条, 上工具条包括监控点名称控件,监控
点类型控件和关闭按钮;预览下工具 条按钮有声音、抓图、云台控制、3D
放大、电子放大、语音对讲、显示监 控点信息、主子码流切换、紧急录像、
鹰眼和即时回放按钮; 自定义按钮定义(括号内为对应 10 进 制 ID 值): 
0x0000(0)- 监控点名称按钮 
0x0001(1)- 监控点类型 
0x0010(16)- 关闭按钮 
0x0100(256)- 预览回放声音 
0x0101(257)- 预览回放抓图 
0x0102(258)- 预览回放电子放大 
0x0103(259)- 预览回放显示监控点信息 
0x0104(260)- 小鹰眼 
0x0200(512)- 预览云台控制 
0x0201(513)- 预览3D放大 
0x0202(514)- 预览语音对讲
0x0203(515)- 预览主子码流切换 
0x0204(516)- 预览紧急录像 
0x205(517)- 预览即时回放 
0x0300(768)- 回放录像剪辑 
0x0301(769)- 回放录像下载
0x0302(770)- 回放录像锁定 
下工具条按指定按钮字符串中按钮 ID 顺序来显示
未指定该字段,则默认显示该模式下 支持的所有工具条按钮;指定为空字
符串时不显示工具条;指定重复、超 出可选范围值、非法值将返回失败;
指定功能不支持的按钮ID将不显示该 按钮(如预览模式指定下载按钮),如
去除不支持的按钮ID后无其它指定按 钮 ID 时,工具条不显示 注 : 0x0201(513)- 预 览
3D 放 大 0x0202(514)- 预 览 语 音 对 讲 0x0302(770)-回放录像锁定 三个按钮
需要openapi 相关接口(参照7.2章节) 支持,若无接口支持,不建议指定相 关按钮。