1. 程式人生 > 實用技巧 >海康安防管理平臺Web視訊對接

海康安防管理平臺Web視訊對接

海康安防管理平臺Web視訊對接

開發文件https://open.hikvision.com/download/5c67f1e2f05948198c909700?type=10
1.視訊分為預覽和回放
2.使用web端的需要安裝外掛 軟體包裡面有
3.使用iframe需要啟動相依的外掛
4.給得demo需要進行配置 key ip port 是的
要展示記錄就是跑在vue上邊

使用的是rtsp的視訊流
由於控制元件展示的時候需要是需要js重新整理的,所以在適配上,比較麻煩,所以就讓某一個外部元素跟著瀏覽器的大小進行變化,視訊控制元件跟著大小變化,海康的視訊控制元件支援後期修改的操作回撥


        <div>
            <div id="playWnd" class="playWnd"></div>
            <div v-show="lodingshow" style="margin: -17px 0;">
                <a-spin tip="Loading...">
                    <div class="spin-content">
                        外掛未啟動,正在嘗試啟動,請稍候...
                    </div>
                </a-spin>
            </div>

            <div v-show="lodingres" class="example">
                <p style="margin: 0;display: inline-block;">沒有檢測到外掛,請安裝外掛後重啟瀏覽器!</p>
                <a-button class="buttonDetails-class" @click="downloadFile()">下載</a-button>
            </div>
        </div>
		 data() {
            return {
                $,
                // 控制視窗個數
                camlength: "1x1",

                // 外掛沒有啟動的顯示樣式
                lodingshow: false,
                lodingres: false,

                usefullData
            }
        },
        created() {
            // 載入播放例項
            this.initPlugin();
            // 監聽resize事件,使外掛視窗尺寸跟隨DIV視窗變化  
            // vue 的onresize
            $(window).resize(() => {
                if (oWebControl != null) {
                    oWebControl.JS_Resize( $('.map').width(), $('.map').height() - 60);
                }
            });

        },
        // 頁面結束的時候關閉顯示視窗
        destroyed() {
            if (oWebControl != null) {
                oWebControl.JS_HideWnd();   // 先讓視窗隱藏,規避可能的外掛視窗滯後於瀏覽器消失問題
                oWebControl.JS_Disconnect().then(() => {  // 斷開與外掛服務連線成功
                    },
                    () => {  // 斷開與外掛服務連線失敗
                    });
            }
        },

		 methods: {
            // 修改佈局 展示畫面
            refusePlay() {
                // 獲取區域列表下的攝像機列表  進行佈局展示
                SubordinateCam({
                    pageNo: 1,
                    pageSize: 1000,
                    regionIndexCode: this.$route.params.id
                }).then(res => {
                    if (res.data.code == 0) {
                        let shuliang = res.data.data.list.length;
                        if (shuliang == 1 || shuliang == 0) {
                            this.camlength = "1x1"
                        } else if (shuliang > 1 && shuliang <= 4) {
                            this.camlength = "2x2"
                        } else if (shuliang > 4 && shuliang <= 9) {
                            this.camlength = "3x3"
                        } else if (shuliang > 9 && shuliang <= 16) {
                            this.camlength = "4x4"
                        } else if (shuliang > 16 && shuliang <= 25) {
                            this.camlength = "5x5"
                        }
                        // 設定攝像頭的佈局
                        oWebControl.JS_RequestInterface({
                            funcName: "setLayout",
                            argument: {layout: this.camlength}
                        }).then(() => {
                            // 有監控點就進行播放
                            if (res.data.data.list.length > 0) {
                                this.$message.success('獲取成功 監控點數量為' + res.data.data.list.length)
                                res.data.data.list.forEach((item, index) => {
                                    oWebControl.JS_RequestInterface({
                                        funcName: "startPreview",
                                        argument: JSON.stringify({
                                            cameraIndexCode: item.cameraIndexCode,                //監控點編號
                                            streamMode: 0,                         //主子碼流標識
                                            transMode: 1,                           //傳輸協議
                                            gpuMode: 0,                               //是否開啟GPU硬解
                                            wndId: index + 1                                     //可指定播放視窗
                                        })
                                    })
                                })
                            } else {
                                this.$message.warning('當前區域無直屬監控點區域')
                                // 停止全部的播放
                                let result = JSON.stringify({
                                    "funcName": "stopAllPreview"
                                }, null, 2)
                                this.requestInterface(result);
                            }
                        })
                    } else {
                        this.$message.error('獲取失敗')
                    }

                })
            },
            // $('.map').width(), $('.map').height() - 60)
            // 建立播放例項
            initPlugin() {
                // eslint-disable-next-line no-undef
                oWebControl = new WebControl({
                    szPluginContainer: "playWnd",                       // 指定容器id
                    iServicePortStart: 15900,                           // 指定起止埠號,建議使用該值
                    iServicePortEnd: 15909,
                    szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11",   // 用於IE10使用ActiveX的clsid
                    cbConnectSuccess: () => {                     // 建立WebControl例項成功
                        oWebControl.JS_StartService("window", {         // WebControl例項建立成功後需要啟動服務
                            dllPath: "./VideoPluginConnect.dll"         // 值"./VideoPluginConnect.dll"寫死
                        }).then(() => {                           // 啟動外掛服務成功
                            oWebControl.JS_SetWindowControlCallback({   // 設定訊息回撥
                                cbIntegrationCallBack: this.cbIntegrationCallBack
                            });
                            oWebControl.JS_CreateWnd("playWnd",  $('.map').width(), $('.map').height() - 60).then(() => { //JS_CreateWnd建立視訊播放視窗,寬高可設定
                                this.init();  // 建立播放例項成功後初始化
                            });
                        }, () => { // 啟動外掛服務失敗
                        });
                    },
                    cbConnectError: () => { // 建立WebControl例項失敗
                        oWebControl = null;
                        // $("#playWnd").html("外掛未啟動,正在嘗試啟動,請稍候...");
                        this.lodingshow = true;
                        // eslint-disable-next-line no-undef
                        WebControl.JS_WakeUp("VideoWebPlugin://"); // 程式未啟動時執行error函式,採用wakeup來啟動程式
                        initCount++;
                        if (initCount < 3) {
                            setTimeout(() => {
                                this.initPlugin();
                            }, 3000)
                        } else {
                            this.lodingshow = false;
                            this.lodingres = true;
                            // $("#playWnd").html("外掛啟動失敗,請檢查外掛是否安裝!");
                        }
                    },
                    cbConnectClose: () => {
                        // 異常斷開:bNormalClose = false
                        // JS_Disconnect正常斷開:bNormalClose = true
                        oWebControl = null;
                    }
                });
            },

            //初始化
            init() {
                // 獲取公鑰的方法
                this.getPubKey(() => {
                    ////////////////////////////////// 請自行修改以下變數值	////////////////////////////////////
                    let appkey = usefullData.appkey;                           //綜合安防管理平臺提供的appkey,必填
                    // 進行相應的加密
                    let secret = this.setEncrypt(usefullData.secret);   //綜合安防管理平臺提供的secret,必填
                    let ip = usefullData.ip;                           //綜合安防管理平臺IP地址,必填
                    let port = usefullData.port;                       //綜合安防管理平臺埠,若啟用HTTPS協議,預設443
                    let playMode = 0;                                  //初始播放模式:0-預覽,1-回放
                    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,256,257,258,259,260,512,513,514,515,516,768,769";  //自定義工具條按鈕
                    let toolBarButtonIDs = "2048,2304,2305,2306,2307,2308,2309,4096,4097,4098,4099,4608,4609"
                    ////////////////////////////////// 請自行修改以上變數值	////////////////////////////////////
                    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,                       //自定義工具條按鈕
                            toolBarButtonIDs:toolBarButtonIDs           //自定義最外層的工具條
                        })
                    }).then(() => {
                        oWebControl.JS_Resize( $('.map').width(), $('.map').height() - 60);  // 初始化後resize一次,規避firefox下首次顯示視窗後外掛視窗未與DIV視窗重合問題
                        // 載入完成後進行佈局的修改 和 攝像頭的展示
                        this.refusePlay();
                    });

                });

            },

            //獲取公鑰
            getPubKey(callback) {
                oWebControl.JS_RequestInterface({
                    funcName: "getRSAPubKey",
                    argument: JSON.stringify({
                        keyLength: 1024
                    })
                }).then((oData) => {
                    console.log(oData);
                    if (oData.responseMsg.data) {
                        pubKey = oData.responseMsg.data;
                        callback()
                    }
                })
            },

            //RSA加密
            setEncrypt(value) {
                // eslint-disable-next-line no-undef
                let encrypt = new JSEncrypt();
                encrypt.setPublicKey(pubKey);
                return encrypt.encrypt(value);
            },

            // 推送訊息
            cbIntegrationCallBack(oData) {
                // if (oData.responseMsg.msg.cameraIndexCode != '') {
                //     this.$router.push({name: 'playbackDetails', params: {id: oData.responseMsg.msg.cameraIndexCode}})
                // }
                this.showCBInfo(JSON.stringify(oData.responseMsg));
            },

            // 設定視窗裁剪,當因滾動條滾動導致視窗需要被遮住的情況下需要JS_CuttingPartWindow部分視窗
            setWndCover() {
                let iWidth = $('.map').width();
                let iHeight = $('.map').height() - 60;
                let oDivRect = $("#playWnd").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 > 1200) ? 1200 : iCoverLeft;
                iCoverTop = (iCoverTop > 600) ? 600 : iCoverTop;
                iCoverRight = (iCoverRight > 1200) ? 1200 : iCoverRight;
                iCoverBottom = (iCoverBottom > 600) ? 600 : iCoverBottom;

                oWebControl.JS_RepairPartWindow(0, 0,  $('.map').width(), $('.map').height() - 60);    // 多1個畫素點防止還原後邊界缺失一個畫素條
                if (iCoverLeft != 0) {
                    oWebControl.JS_CuttingPartWindow(0, 0, iCoverLeft, 600);
                }
                if (iCoverTop != 0) {
                    oWebControl.JS_CuttingPartWindow(0, 0, $('.map').width(), iCoverTop);    // 多剪掉一個畫素條,防止出現剪掉一部分視窗後出現一個畫素條
                }
                if (iCoverRight != 0) {
                    oWebControl.JS_CuttingPartWindow($('.map').width() - iCoverRight, 0, iCoverRight, 600);
                }
                if (iCoverBottom != 0) {
                    oWebControl.JS_CuttingPartWindow(0, 600 - iCoverBottom, $('.map').width(), iCoverBottom);
                }
            },

            // 執行字串方法
            // value為字串,JS_RequestInterface僅接收json格式的變數,且需要先解析出argument,並且將argument欄位的內容轉為字串
            requestInterface(value) {
                this.isJSON(value);
                let JsonParam = JSON.parse(value);
                let JsonArgument = JsonParam.argument;
                JsonParam.argument = JSON.stringify(JsonArgument);

                oWebControl.JS_RequestInterface(JsonParam).then((oData) => {
                    this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
                });
            },

            // 顯示介面返回的訊息及外掛回撥資訊
            showCBInfo(szInfo, type) {
                if (type === 'error') {
                    szInfo = "<div style='color: red;'>" + this.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") + " " + szInfo + "</div>";
                } else {
                    szInfo = "<div>" + this.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") + " " + szInfo + "</div>";
                }
                $("#cbInfo").html(szInfo + $("#cbInfo").html());
            },

            // 判斷字串是否為json
            isJSON(str) {
                if (typeof str == 'string') {
                    try {
                        let obj = JSON.parse(str);
                        if (typeof obj == 'object' && obj) {
                            return true;
                        } else {
                            this.showCBInfo("param is not the correct JSON message");
                            return false;
                        }
                    } catch (e) {
                        this.showCBInfo("param is not the correct JSON message");
                        return false;
                    }
                }
            },

            // 格式化時間
            dateFormat(oDate, fmt) {
                let 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 (let 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;
            },
            // 下載檔案到本地
            downloadFile() {
                var a = document.createElement('a')
                // var blob = new Blob([content])
                // var url = window.URL.createObjectURL(blob)
                a.href = '控制元件下載地址'
                a.download = '視訊外掛'
                a.click()
                // window.URL.revokeObjectURL(url)
            },

        }

注意: 首先他給得Demo寫的還是蠻清楚的,註釋都比較好
裡面的請求我沒有刪除
我覺得都會用到
首先這個視訊載入是直接使用的安防管理平臺的監控點,進行渲染的,所以首先需要進行相應的請求,獲取攝像頭列表的資料,進行展示控制元件的佈局,然後進行視訊預覽的播放。
其餘的文件裡面的寫的很清楚