海康威視的視頻web端(vue開發)的實時預覽、錄像回放和(hé)頁面拖拽 - 新聞資(zī)訊 - 雲南小程序開發|雲南軟件開發|雲南網站(zhàn)建設-西山區知普網絡科技工作室

159-8711-8523

雲南網建設/小程序開發/軟件開發

知識

不管是網站(zhàn),軟件還是小程序,都要直接或間接能為您産生價值,我們在追求其視覺表現的同時,更側重于功能的便捷,營銷的便利,運營的高效,讓網站(zhàn)成為營銷工具,讓軟件能切實提升企業(yè)内部管理水平和(hé)效率。優秀的程序為後期升級提供便捷的支持!

您當前位置>首頁 » 新聞資(zī)訊 » 網站(zhàn)建設 >

海康威視的視頻web端(vue開發)的實時預覽、錄像回放和(hé)頁面拖拽

發表時間:2019-11-20

發布人:葵宇科技

浏覽次數:424

效果圖

實現步驟

1. 安裝海康web插件,去海康威視官網上下(xià)載,官方不支持Mac,隻支持Windows

https://open.hikvision.com/

2. 在index.html引入js文(wén)件,安裝包裡面有

<script src="static/jquery-1.12.4.min.js"></script>
<script src="static/jsencrypt.min.js"></script>
<script src="static/jsWebControl-1.0.0.min.js"></script>

3. 代碼實現,可(kě)兼容谷歌、火狐、360、edge

<template>
	<div id="videoPlayerBox" ref="videoPlayerBox"
		:style="{'width': width + 'px', 'height': height + 'px', 'top': top + 'px', 'left': left + 'px'}">
		<div class="header">
			<div class="el-dialog__title" @mousedown="onmousedown" @mouseleave="onmouseleave">
				<!-- {{ monitorDeviceName }} -->
				監控點
			</div>
			<span class="closeBtn" @click="handleClose">×</span>
		</div>
		<div class="topbutton">
			<span class="topBtns" :class="playMode === 0 ? 'activeBtn' : ''" @click="previewClick">預覽</span>
			<span class="topBtns" :class="playMode === 1 ? 'activeBtn' : ''" @click="playBack">回放</span>
		</div>
		<div id="playBox" v-html="oWebControl === null ? playText : ''">
		</div>
	</div>
</template>

<script>
export default {
	name: 'videoPlayer',
	props: [
		'videoVisible',
		'monitorDeviceNo',
		'monitorDeviceName'
	],
	data() {
		return {
			oWebControl: null,
			pubKey: '', // 公鑰
			appkey: '',
			secret: '',
			ip: '',
			port: '',
			width: 700,
			height: 400, // 彈框高度
			playHeight: 360,
			layout: '1x1',
			left: '',
			top: '',
			buttonIDs: '0,16,256,257,515',
			initCount: 0,
			playMode: 0, // 0 預覽 1回放
			playText: '啟動(dòng)中(zhōng)。。。',
			cameraIndexCode: this.monitorDeviceNo || '' // 監控點編号
		}
	},
	methods: {
		handleClose() {
			if (this.oWebControl) {
				this.oWebControl.JS_RequestInterface({
						funcName: "stopAllPreview"
				});
				this.oWebControl.JS_HideWnd();
				this.oWebControl.JS_Disconnect().then(
						() => {  // 斷開與插件服務連接成功
						}, 
						() => {  // 斷開與插件服務連接失敗 
						});
				this.oWebControl = null;
			}
			this.$emit('close');
		},
		// 推送消息
		cbIntegrationCallBack(oData) {
			console.log(oData, '推送消息');
		},
		// RSA加密
		setEncrypt (value) {
			/* eslint-disable */
			let encrypt = new JSEncrypt();
			encrypt.setPublicKey(this.pubKey);
			return encrypt.encrypt(value);
		},
		initPlugin(callback) {
			/* eslint-disable */
			let that = this;
			this.oWebControl = new WebControl({
					szPluginContainer: "playBox",                       // 指定容器(qì)id
					iServicePortStart: 15900,                           // 指定起止端口号,建議使用該值
					iServicePortEnd: 15909,
					szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11",  // 用于IE10使用ActiveX的clsid
					cbConnectSuccess: function () {                     // 創建WebControl實例成功
						that.oWebControl.JS_StartService("window", {      // WebControl實例創建成功後需要啟動(dòng)服務
							dllPath: "./VideoPluginConnect.dll"             // 值"./VideoPluginConnect.dll"寫死 
						}).then(function () {                             // 啟動(dòng)插件服務成功
							that.oWebControl.JS_SetWindowControlCallback({  // 設置消息回調
								cbIntegrationCallBack: that.cbIntegrationCallBack
							});
							
							that.oWebControl.JS_CreateWnd("playBox", that.width, that.playHeight).then(function () { // JS_CreateWnd創建視頻播放窗口,寬高可(kě)設定
								that.init(callback);  // 創建播放實例成功後初始化
							});
						}, function () { // 啟動(dòng)插件服務失敗
						});
					},
					cbConnectError: function () { // 創建WebControl實例失敗
						that.oWebControl = null;
						that.playText = '插件未啟動(dòng),正在嘗試啟動(dòng),請稍候...';
						WebControl.JS_WakeUp("VideoWebPlugin://"); // 程序未啟動(dòng)時執行error函數,采用wakeup來啟動(dòng)程序
						that.initCount++;
						if (that.initCount < 3) {
							setTimeout(function () {
								that.initPlugin();
							}, 3000)
						} else {
							that.playText = '插件啟動(dòng)失敗,請檢查插件是否安裝!<a target="_blank" style="color: #30a8ff;text-decoration: underline;" href="http://xx.com/VideoWebPlugin.zip">下(xià)載地址(軟件大小:62.7MB)</a>';
						}
					},
					cbConnectClose: function (bNormalClose) {
						// 異常斷開:bNormalClose = false
						// JS_Disconnect正常斷開:bNormalClose = true	
						console.log("cbConnectClose");
						that.oWebControl = null;
					}
			});
		},
		// 獲取公鑰
		getPubKey (callback) {
			this.oWebControl.JS_RequestInterface({
					funcName: "getRSAPubKey",
					argument: JSON.stringify({
							keyLength: 1024
					})
			}).then((oData) => {
					if (oData.responseMsg.data) {
							this.pubKey = oData.responseMsg.data;
							callback()
					}
			})
		},
		init(callback) {
			let that = this;
			this.getPubKey(() => {
					//  請自行修改以下(xià)變量值	
					let appkey = this.appkey;                           // 綜合安防管理平台提供的appkey,必填
					let secret = that.setEncrypt(this.secret);// 綜合安防管理平台提供的secret,必填
					let ip = this.ip;                           // 綜合安防管理平台IP地址,必填
					let playMode = this.playMode;                                  // 初始播放模式:0-預覽,1-回放
					let port = 443;                                    // 綜合安防管理平台端口,若啟用HTTPS協議,默認443
					let snapDir = "D:\\SnapDir";                       // 抓圖存儲路(lù)徑
					let videoDir = "D:\\VideoDir";                     // 緊急錄像或錄像剪輯存儲路(lù)徑
					let layout = this.layout;                          // playMode指定模式的布局
					let enableHTTPS = 1;                               // 是否啟用HTTPS協議與綜合安防管理平台交互,是為1,否為0
					let encryptedFields = 'secret';					   				 // 加密字段,默認加密領域為secret
					let showToolbar = 1;                               // 是否顯示工具欄,0-不顯示,非0-顯示
					let showSmart = 1;                                 // 是否顯示智能信息(如(rú)配置移動(dòng)偵測後畫面上的線框),0-不顯示,非0-顯示
					let buttonIDs = this.buttonIDs;                    // 自定義工具條按鈕
					// /// 請自行修改以上變量值	
					that.oWebControl.JS_RequestInterface({
							funcName: "init",
							argument: JSON.stringify({
									appkey: appkey,                            // API網關(guān)提供的appkey
									secret: secret,                            // API網關(guān)提供的secret
									ip: ip,                                    // API網關(guān)IP地址
									playMode: playMode,                        // 播放模式(決定顯示預覽還是回放界面)
									port: port,                                // 端口
									snapDir: snapDir,                          // 抓圖存儲路(lù)徑
									videoDir: videoDir,                        // 緊急錄像或錄像剪輯存儲路(lù)徑
									layout: layout,                            // 布局
									enableHTTPS: enableHTTPS,                  // 是否啟用HTTPS協議
									encryptedFields: encryptedFields,          // 加密字段
									showToolbar: showToolbar,                  // 是否顯示工具欄
									showSmart: showSmart,                      // 是否顯示智能信息
									buttonIDs: buttonIDs                       // 自定義工具條按鈕
							})
					}).then((oData) => {
							that.oWebControl.JS_Resize(that.width, that.playHeight);  // 初始化後resize一次,規避firefox下(xià)首次顯示窗口後插件窗口未與DIV窗口重合問(wèn)題
							if (callback) {
								callback();
							}
					});
			});
		},
		// 視頻預覽功能
		previewClick() {
			if (!this.oWebControl) {
				return;
			}
			// 如(rú)果是回放,重新初始化
			if (this.playMode === 1) {
				this.playMode = 0;
				this.oWebControl.JS_HideWnd();
				this.initPlugin(() => {
					this.previewVideo();
				});
				
			} else if (this.playMode === 0) {
				this.previewVideo();
			}
		},
		previewVideo() {
			let cameraIndexCode = this.cameraIndexCode;             // 獲取輸入的監控點編号值,必填
			let streamMode = 0;                                     // 主子(zǐ)碼流标識:0-主碼流,1-子(zǐ)碼流
			let transMode = 0;                                      // 傳輸協議:0-UDP,1-TCP
			let gpuMode = 0;                                        // 是否啟用GPU硬解,0-不啟用,1-啟用
			let wndId = -1;                                         // 播放窗口序号(在2x2以上布局下(xià)可(kě)指定播放窗口)
			
			this.oWebControl.JS_RequestInterface({
					funcName: "startPreview",
					argument: JSON.stringify({
							cameraIndexCode: cameraIndexCode.trim(),        // 監控點編号
							streamMode: streamMode,                         // 主子(zǐ)碼流标識
							transMode: transMode,                           // 傳輸協議
							gpuMode: gpuMode,                               // 是否開啟GPU硬解
							wndId: wndId                                    // 可(kě)指定播放窗口
					})
			})
		},
		// 回放
		playBack() {
			if (!this.oWebControl) {
				return;
			}
			// 如(rú)果是預覽
			if (this.playMode === 0) {
				this.playMode = 1;
				this.oWebControl.JS_HideWnd();
				this.initPlugin(() => {
					this.backVideo();
				});
			} else if (this.playMode === 1) {
					this.backVideo();
			}
		},
		backVideo() {
			let cameraIndexCode = this.cameraIndexCode;
			// 前30天
			let date = new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000);
			let month = date.getMonth() + 1 < 10 ? ('0' + (date.getMonth() + 1)) : (date.getMonth()+ 1);
			// 開始時間當天00點
			let str = date.getFullYear() + '/' + month + '/' + date.getDate() + ' 00:00:00'
			let startTime = String(parseInt(new Date(str).getTime() / 1000) -  3 * 60 * 60);
			let endTime = String(parseInt(date.getTime() / 1000));
			this.oWebControl.JS_RequestInterface({
				funcName: "startPlayback",
				argument: JSON.stringify({
					cameraIndexCode: cameraIndexCode.trim(), // 監控點編号
					startTimeStamp: startTime, // 錄像查詢開始時間戳,單位:秒
					endTimeStamp: endTime, // 錄像查詢結束時間戳,單位:秒
					recordLocation: 1, // 錄像存儲類型 0-中(zhōng)心存儲 1-設備存儲
					transMode: 0, // 傳輸協議 ,0-UDP 1-TCP
					gpuMode: 0, // 是否開啟 GPU 硬解,0-不開啟 1-開啟
					wndId: -1                         //可(kě)指定播放窗口
				})
			});
		},
		// 設置窗口裁剪,當因滾動(dòng)條滾動(dòng)導緻窗口需要被遮住的情況下(xià)需要JS_CuttingPartWindow部分窗口
		setWndCover() {
			let iWidth = $(window).width();
			let iHeight = $(window).height();
			let oDivRect = $("#playBox").get(0).getBoundingClientRect();
			let iCoverLeft = (oDivRect.left < 0) ? Math.abs(oDivRect.left) : 0;
			let iCoverTop = (oDivRect.top < 0) ? Math.abs(oDivRect.top) : 0;
			let iCoverRight = (oDivRect.right - iWidth > 0) ? Math.round(oDivRect.right - iWidth) : 0;
			let iCoverBottom = (oDivRect.bottom - iHeight > 0) ? Math.round(oDivRect.bottom - iHeight) : 0;

			iCoverLeft = (iCoverLeft > this.width) ? this.width : iCoverLeft;
			iCoverTop = (iCoverTop > this.playHeight) ? this.playHeight : iCoverTop;
			iCoverRight = (iCoverRight > this.width) ? this.width : iCoverRight;
			iCoverBottom = (iCoverBottom > this.playHeight) ? this.playHeight : iCoverBottom;

			this.oWebControl.JS_RepairPartWindow(0, 0, (this.width + 1), this.playHeight);    // 多1個(gè)像素點防止還原後邊界缺失一個(gè)像素條
			if (iCoverLeft != 0) {
				this.oWebControl.JS_CuttingPartWindow(0, 0, iCoverLeft, this.playHeight);
			}
			if (iCoverTop != 0) {
					this.oWebControl.JS_CuttingPartWindow(0, 0, (this.width + 1), iCoverTop);    // 多剪掉一個(gè)像素條,防止出現剪掉一部分窗口後出現一個(gè)像素條
			}
			if (iCoverRight != 0) {
					this.oWebControl.JS_CuttingPartWindow(this.width - iCoverRight, 0, iCoverRight, this.playHeight);
			}
			if (iCoverBottom != 0) {
					this.oWebControl.JS_CuttingPartWindow(0, this.playHeight - iCoverBottom, this.width, iCoverBottom);
			}
		},
		// 拖拽窗口
		onmousedown (e) {
      let that = this;
			let cWidth = document.body.clientWidth;
			let cHeight = document.body.clientHeight;
      this.$refs.videoPlayerBox.onmousemove = function (el) {
        let ev = el || window.event;
				ev.preventDefault();
				// 解決點擊标題窗口抖動(dòng)的問(wèn)題
				if (Math.abs(ev.movementX) === 0 && Math.abs(ev.movementY) === 0) {
					return;
				}
        that.left += ev.movementX;
				that.top += ev.movementY;
				// 頂部不能超出,左側、右側、底部可(kě)以超出一半
				if (that.top < 0) {
					that.top = 0;
				}
				if (that.top > (cHeight - that.height / 2)) {
					that.top = cHeight - that.height / 2;
				}
				if (that.left < -that.width / 2) {
					that.left = -that.width / 2;
				}
				if (that.left > (cWidth - that.width / 2)) {
					that.left = (cWidth - that.width / 2);
				}
				that.oWebControl.JS_Resize(that.width, that.playHeight);
      }
      this.$refs.videoPlayerBox.onmouseup = function () {
        this.onmousemove = null;
        this.onmouseup = null;
      }
      // 阻止默認事件
      if (e.preventDefault) {
        e.preventDefault()
      } else {
        return false
      }
		},
		onmouseleave(e) {
            // 拖拽過快鼠标劃出标題位置,重新拖拽是,鼠标還未移入标題,由于上一次的onmouseup方法沒有執行,導緻鼠标靠近彈框,彈框移動(dòng),解決方法,給onmousemove和(hé)onmouseup賦值為null
			this.$refs.videoPlayerBox.onmousemove = null;
			this.$refs.videoPlayerBox.onmouseup = null;
            // 解決拖拽過快,播放器(qì)殘影問(wèn)題
			this.oWebControl.JS_Resize(this.width, this.playHeight);
		}
	},
	mounted() {
		let hksystem = JSON.parse(sessionStorage.getItem('hksystem'));
		this.appkey = hksystem.appKey;
		this.secret = hksystem.appSecret;
		this.ip = hksystem.host.split(':')[0];
		this.port = hksystem.host.split(':')[1];
		// 設置top left
		let bodyW = document.body.clientWidth;
    let bodyH = document.body.clientHeight;
		this.left = bodyW / 2 - this.width / 2;
		this.top = bodyH / 2 - this.height / 2;
		
		this.initPlugin(() => {
					this.previewVideo();
				});
		// 監聽resize事件,使插件窗口尺寸跟随DIV窗口變化
		$(window).resize(() => { 
				if (this.oWebControl != null) {
						this.oWebControl.JS_Resize(this.width, this.playHeight);
						this.setWndCover();
				}
		});
		
		// 監聽滾動(dòng)條scroll事件,使插件窗口跟随浏覽器(qì)滾動(dòng)而移動(dòng)
		$(window).scroll(() => {
				if (this.oWebControl != null) {
						this.oWebControl.JS_Resize(this.width, this.playHeight);
						this.setWndCover();
				}
		});
		// 标簽關(guān)閉
		$(window).unload(() => {
			if (this.oWebControl != null) {
				this.oWebControl.JS_HideWnd();   // 先讓窗口隐藏,規避可(kě)能的插件窗口滞後于浏覽器(qì)消失問(wèn)題 
				this.oWebControl.JS_Disconnect().then(
					() => {  // 斷開與插件服務連接成功
					}, 
					() => {  // 斷開與插件服務連接失敗 
					}
				);
			}
		});
	},
	watch: {
		monitorDeviceNo: {
			handler(newV, oldV) {
				this.cameraIndexCode = newV;
				if (newV && this.playMode === 0) {
					this.previewVideo();
				} else if (newV && this.playMode === 1) {
					this.backVideo();
				}
			}
		}
	}
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
#videoPlayerBox
	position fixed
	z-index 4012
	background-color #0D1F3A
	.header
		padding 10px 20px
		background-color #142C50
		position relative
		.el-dialog__title
			height 24px
			text-align center
			background-color #142C50
			color #fff
			font-size 14px
			cursor pointer
		.closeBtn
			position absolute 
			top 10px
			right 10px
			padding 2px 4px
			border 1px dotted #ccc
			color #fff
			font-size 18px
			cursor pointer
			&:hover
				color #4BA2FF
	.topbutton
		height 26px
		padding-top 6px
		padding-left 14px
		background-color #0D1F3A
		cursor pointer
		.topBtns
			padding 0 12px 6px
			border-bottom 1px solid #0D1F3A
			color #fff
		.activeBtn
			color #4BA2FF
			border-color #4BA2FF
	#playBox
		width 100%
		height 360px
		color red
</style>

開發中(zhōng)遇到的問(wèn)題及解決方法

1. 創建實例失敗時重新喚起插件

文(wén)檔錯誤 oWebControl.JS_WakeUp("VideoWebPlugin://")

正确方法如(rú)下(xià)

WebControl.JS_WakeUp("VideoWebPlugin://"); // 程序未啟動(dòng)時執行

2. 産品要求彈框顯示後直接進行預覽,不需要再次點擊

實現過程

先初始化 this.initPlugin()

再執行預覽方法 this.previewVideo()

未能實現,因為初始化方法是異步的

解決方法,給初始化方法傳遞一個(gè)回調函數
this.initPlugin(() => {
this.previewVideo();
});

3. 多窗口實時預覽實現,效果圖如(rú)下(xià)

切換到2x2模式,監聽父組件傳遞過來的監控點編号,調預覽方法

watch: {
		monitorDeviceNo: {
			handler(newV, oldV) {
				this.cameraIndexCode = newV;
				if (newV && this.playMode === 0) {
					this.previewVideo();
				} else if (newV && this.playMode === 1) {
					this.backVideo();
				}
			}
		}
	}

關(guān)閉彈框的是,需要調用停止所有預覽的API

相關(guān)案例查看更多