【vue2】前端如何播放rtsp 視頻流,拿到rtsp視頻流地址如何處理,海康視頻rtsp h264 如何播放

慈雲數據 1年前 (2024-04-02) 技術支持 87 0

文章目錄

    • 測試
    • 以vue2 爲例
      • 新建 webrtcstreamer.js
      • 下載webrtc-streamer
      • video.vue
      • 頁面中調用

        最近在寫vue2 項目其中有個需求是實時播放攝像頭的視頻,攝像頭是 海康的設備,搞了很長時間終于監控視頻出來了,記錄一下,放置下次遇到。文章有點長,略顯啰嗦請耐心看完。

        測試

        測試?測試什麽?測試rtsp視頻流能不能播放。

        video mediaplay官網 即(VLC)

        下載、安裝完VLC後,打開VLC 點擊媒體 -> 打開網絡串流

        在這裏插入圖片描述

        将rtsp地址粘貼進去

        在這裏插入圖片描述

        不能播放的話,rtsp視頻流地址有問題。

        注意:視頻可以播放也要查看視頻的格式,如下

        右擊視頻選擇工具->編解碼器信息

        在這裏插入圖片描述

        如果編解碼是H264的,那麽我的這種方法可以。如果是H265或者其他的話就要登錄海康後台修改一下

        在這裏插入圖片描述

        以vue2 爲例

        新建 webrtcstreamer.js

        在public文件夾下新建webrtcstreamer.js文件,直接複制粘貼,無需修改

        Python
        var WebRtcStreamer = (function() {
        /** 
         * Interface with WebRTC-streamer API
         * @constructor
         * @param {string} videoElement - id of the video element tag
         * @param {string} srvurl -  url of webrtc-streamer (default is current location)
        */
        var WebRtcStreamer = function WebRtcStreamer (videoElement, srvurl) {
        	if (typeof videoElement === "string") {
        		this.videoElement = document.getElementById(videoElement);
        	} else {
        		this.videoElement = videoElement;
        	}
        	this.srvurl           = srvurl || location.protocol+"//"+window.location.hostname+":"+window.location.port;
        	this.pc               = null;    
        	this.mediaConstraints = { offerToReceiveAudio: true, offerToReceiveVideo: true };
        	this.iceServers = null;
        	this.earlyCandidates = [];
        }
        WebRtcStreamer.prototype._handleHttpErrors = function (response) {
            if (!response.ok) {
                throw Error(response.statusText);
            }
            return response;
        }
        /** 
         * Connect a WebRTC Stream to videoElement 
         * @param {string} videourl - id of WebRTC video stream
         * @param {string} audiourl - id of WebRTC audio stream
         * @param {string} options -  options of WebRTC call
         * @param {string} stream  -  local stream to send
        */
        WebRtcStreamer.prototype.connect = function(videourl, audiourl, options, localstream) {
        	this.disconnect();
        	
        	// getIceServers is not already received
        	if (!this.iceServers) {
        		console.log("Get IceServers");
        		
        		fetch(this.srvurl + "/api/getIceServers")
        			.then(this._handleHttpErrors)
        			.then( (response) => (response.json()) )
        			.then( (response) =>  this.onReceiveGetIceServers(response, videourl, audiourl, options, localstream))
        			.catch( (error) => this.onError("getIceServers " + error ))
        				
        	} else {
        		this.onReceiveGetIceServers(this.iceServers, videourl, audiourl, options, localstream);
        	}
        }
        /** 
         * Disconnect a WebRTC Stream and clear videoElement source
        */
        WebRtcStreamer.prototype.disconnect = function() {		
        	if (this.videoElement?.srcObject) {
        		this.videoElement.srcObject.getTracks().forEach(track => {
        			track.stop()
        			this.videoElement.srcObject.removeTrack(track);
        		});
        	}
        	if (this.pc) {
        		fetch(this.srvurl + "/api/hangup?peerid=" + this.pc.peerid)
        			.then(this._handleHttpErrors)
        			.catch( (error) => this.onError("hangup " + error ))
        		
        		try {
        			this.pc.close();
        		}
        		catch (e) {
        			console.log ("Failure close peer connection:" + e);
        		}
        		this.pc = null;
        	}
        }    
        /*
        * GetIceServers callback
        */
        WebRtcStreamer.prototype.onReceiveGetIceServers = function(iceServers, videourl, audiourl, options, stream) {
        	this.iceServers       = iceServers;
        	this.pcConfig         = iceServers || {"iceServers": [] };
        	try {            
        		this.createPeerConnection();
        		var callurl = this.srvurl + "/api/call?peerid=" + this.pc.peerid + "&url=" + encodeURIComponent(videourl);
        		if (audiourl) {
        			callurl += "&audiourl="+encodeURIComponent(audiourl);
        		}
        		if (options) {
        			callurl += "&options="+encodeURIComponent(options);
        		}
        		
        		if (stream) {
        			this.pc.addStream(stream);
        		}
                        // clear early candidates
        		this.earlyCandidates.length = 0;
        		
        		// create Offer
        		this.pc.createOffer(this.mediaConstraints).then((sessionDescription) => {
        			console.log("Create offer:" + JSON.stringify(sessionDescription));
        			
        			this.pc.setLocalDescription(sessionDescription)
        				.then(() => {
        					fetch(callurl, { method: "POST", body: JSON.stringify(sessionDescription) })
        						.then(this._handleHttpErrors)
        						.then( (response) => (response.json()) )
        						.catch( (error) => this.onError("call " + error ))
        						.then( (response) =>  this.onReceiveCall(response) )
        						.catch( (error) => this.onError("call " + error ))
        				
        				}, (error) => {
        					console.log ("setLocalDescription error:" + JSON.stringify(error)); 
        				});
        			
        		}, (error) => { 
        			alert("Create offer error:" + JSON.stringify(error));
        		});
        	} catch (e) {
        		this.disconnect();
        		alert("connect error: " + e);
        	}	    
        }
        WebRtcStreamer.prototype.getIceCandidate = function() {
        	fetch(this.srvurl + "/api/getIceCandidate?peerid=" + this.pc.peerid)
        		.then(this._handleHttpErrors)
        		.then( (response) => (response.json()) )
        		.then( (response) =>  this.onReceiveCandidate(response))
        		.catch( (error) => this.onError("getIceCandidate " + error ))
        }
        					
        /*
        * create RTCPeerConnection 
        */
        WebRtcStreamer.prototype.createPeerConnection = function() {
        	console.log("createPeerConnection  config: " + JSON.stringify(this.pcConfig));
        	this.pc = new RTCPeerConnection(this.pcConfig);
        	var pc = this.pc;
        	pc.peerid = Math.random();		
        	
        	pc.onicecandidate = (evt) => this.onIceCandidate(evt);
        	pc.onaddstream    = (evt) => this.onAddStream(evt);
        	pc.oniceconnectionstatechange = (evt) => {  
        		console.log("oniceconnectionstatechange  state: " + pc.iceConnectionState);
        		if (this.videoElement) {
        			if (pc.iceConnectionState === "connected") {
        				this.videoElement.style.opacity = "1.0";
        			}			
        			else if (pc.iceConnectionState === "disconnected") {
        				this.videoElement.style.opacity = "0.25";
        			}			
        			else if ( (pc.iceConnectionState === "failed") || (pc.iceConnectionState === "closed") )  {
        				this.videoElement.style.opacity = "0.5";
        			} else if (pc.iceConnectionState === "new") {
        				this.getIceCandidate();
        			}
        		}
        	}
        	pc.ondatachannel = function(evt) {  
        		console.log("remote datachannel created:"+JSON.stringify(evt));
        		
        		evt.channel.onopen = function () {
        			console.log("remote datachannel open");
        			this.send("remote channel openned");
        		}
        		evt.channel.onmessage = function (event) {
        			console.log("remote datachannel recv:"+JSON.stringify(event.data));
        		}
        	}
        	pc.onicegatheringstatechange = function() {
        		if (pc.iceGatheringState === "complete") {
        			const recvs = pc.getReceivers();
        		
        			recvs.forEach((recv) => {
        			  if (recv.track && recv.track.kind === "video") {
        				console.log("codecs:" + JSON.stringify(recv.getParameters().codecs))
        			  }
        			});
        		  }
        	}
        	try {
        		vAR DataChannel = pc.createDataChannel("ClientDataChannel");
        		dataChannel.onopen = function() {
        			console.log("local datachannel open");
        			this.send("local channel openned");
        		}
        		dataChannel.onmessage = function(evt) {
        			console.log("local datachannel recv:"+JSON.stringify(evt.data));
        		}
        	} catch (e) {
        		console.log("Cannor create datachannel error: " + e);
        	}	
        	
        	console.log("Created RTCPeerConnnection with config: " + JSON.stringify(this.pcConfig) );
        	return pc;
        }
        /*
        * RTCPeerConnection IceCandidate callback
        */
        WebRtcStreamer.prototype.onIceCandidate = function (event) {
        	if (event.candidate) {
        		if (this.pc.currentRemoteDescription)  {
        			this.addIceCandidate(this.pc.peerid, event.candidate);					
        		} else {
        			this.earlyCandidates.push(event.candidate);
        		}
        	} 
        	else {
        		console.log("End of candidates.");
        	}
        }
        WebRtcStreamer.prototype.addIceCandidate = function(peerid, candidate) {
        	fetch(this.srvurl + "/api/addIceCandidate?peerid="+peerid, { method: "POST", body: JSON.stringify(candidate) })
        		.then(this._handleHttpErrors)
        		.then( (response) => (response.json()) )
        		.then( (response) =>  {console.log("addIceCandidate ok:" + response)})
        		.catch( (error) => this.onError("addIceCandidate " + error ))
        }
        				
        /*
        * RTCPeerConnection AddTrack callback
        */
        WebRtcStreamer.prototype.onAddStream = function(event) {
        	console.log("Remote track added:" +  JSON.stringify(event));
        	
        	this.videoElement.srcObject = event.stream;
        	var promise = this.videoElement.play();
        	if (promise !== undefined) {
        	  promise.catch((error) => {
        		console.warn("error:"+error);
        		this.videoElement.setAttribute("controls", true);
        	  });
        	}
        }
        		
        /*
        * AJAX /call callback
        */
        WebRtcStreamer.prototype.onReceiveCall = function(dataJson) {
        	console.log("offer: " + JSON.stringify(dataJson));
        	var descr = new RTCSessionDescription(dataJson);
        	this.pc.setRemoteDescription(descr).then(() =>  { 
        			console.log ("setRemoteDescription ok");
        			while (this.earlyCandidates.length) {
        				var candidate = this.earlyCandidates.shift();
        				this.addIceCandidate(this.pc.peerid, candidate);				
        			}
        		
        			this.getIceCandidate()
        		}
        		, (error) => { 
        			console.log ("setRemoteDescription error:" + JSON.stringify(error)); 
        		});
        }	
        /*
        * AJAX /getIceCandidate callback
        */
        WebRtcStreamer.prototype.onReceiveCandidate = function(dataJson) {
        	console.log("candidate: " + JSON.stringify(dataJson));
        	if (dataJson) {
        		for (var i=0; i      { console.log ("addIceCandidate OK"); }
        				, (error) => { console.log ("addIceCandidate error:" + JSON.stringify(error)); } );
        		}
        		this.pc.addIceCandidate();
        	}
        }
        /*
        * AJAX callback for Error
        */
        WebRtcStreamer.prototype.onError = function(status) {
        	console.log("onError:" + status);
        }
        return WebRtcStreamer;
        })();
        if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
        	window.WebRtcStreamer = WebRtcStreamer;
        }
        if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        	module.exports = WebRtcStreamer;
        }
        

        下載webrtc-streamer

        資源在最上面

        也可以去github上面下載:webrtc-streamer

        下載完後解壓,打開,啓動

        在這裏插入圖片描述

        出現下面這個頁面就是啓動成功了,留意這裏的端口号,就是我選出來的部分,一般都是默認8000,不排除其他情況

        在這裏插入圖片描述

        檢查一下也沒用啓動成功,http://127.0.0.1:8000/ 粘貼到浏覽器地址欄回車查看,啓動成功能看到電腦當前頁面(這裏的8000就是啓動的端口号,啓動的是多少就訪問多少)

        video.vue

        新建video.js (位置自己決定,後面要引入的)

        video.js中要修改兩個地方,第一個是引入webrtcstreamer.js路徑,第二個地方是IP地址要要修改爲自己的ip加上啓動的端口号(即上面的8000),不知道電腦ip地址的看下面一行

        怎麽查看自己的ip地址打開cmd 黑窗口(即dos窗口),輸入ipconfig回車,在裏面找到 IPv4 地址 就是了

        Python
          
            
            
          
        
        
        import WebRtcStreamer from "../../public/webrtcstreamer";
        export default {
          name: "videoCom",
          props: {
            rtsp: {
              type: String,
              required: true,
            },
            isOn: {
              type: Boolean,
              default: false,
            },
            spareId: {
              type: Number,
            },
            selectStatus: {
              type: Boolean,
              default: false,
            },
          },
          data() {
            return {
              socket: null,
              result: null, // 返回值
              pic: null,
              webRtcServer: null,
              clickCount: 0, // 用來計數點擊次數
            };
          },
          watch: {
            rtsp() {
              // do something
              console.log(this.rtsp);
              this.webRtcServer.disconnect();
              this.initVideo();
            },
          },
          destroyed() {
            this.webRtcServer.disconnect();
          },
          beforeCreate() {
            window.onbeforeunload = () => {
              this.webRtcServer.disconnect();
            };
          },
          created() {},
          mounted() {
            this.initVideo();
          },
          methods: {
            initVideo() {
              try {
                //連接後端的IP地址和端口
                this.webRtcServer = new WebRtcStreamer(
                  this.$refs.video,
                  `http://192.168.0.24:8000`
                );
                //向後端發送rtsp地址
                this.webRtcServer.connect(this.rtsp);
              } catch (error) {
                console.log(error);
              }
            },
            /* 處理雙擊 單機 */
            dbClick() {
              this.clickCount++;
              if (this.clickCount === 2) {
                this.btnFull(); // 雙擊全屏
                this.clickCount = 0;
              }
              setTimeout(() => {
                if (this.clickCount === 1) {
                  this.clickCount = 0;
                }
              }, 250);
            },
            /* 視頻全屏 */
            btnFull() {
              const elVideo = this.$refs.video;
              if (elVideo.webkitRequestFullScreen) {
                elVideo.webkitRequestFullScreen();
              } else if (elVideo.mozRequestFullScreen) {
                elVideo.mozRequestFullScreen();
              } else if (elVideo.requestFullscreen) {
                elVideo.requestFullscreen();
              }
            },
            /* 
            ison用來判斷是否需要更換視頻流
            dbclick函數用來雙擊放大全屏方法
            */
            handleClickVideo() {
              if (this.isOn) {
                this.$emit("selectVideo", this.spareId);
                this.dbClick();
              } else {
                this.btnFull();
              }
            },
          },
        };
        
        
        .active-video-border {
          border: 2px salmon solid;
        }
        #video-contianer {
          position: relative;
          // width: 100%;
          // height: 100%;
          .video {
            // width: 100%;
            // height: 100%;
            // object-fit: cover;
          }
          .mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
          }
        }
        
        

        頁面中調用

        在頁面中引入video.vue,并注冊。将rtsp視頻地址傳過去就好了,要顯示幾個視頻就調用幾次

        在這裏插入圖片描述

        回到頁面看,rtsp視頻已經可以播放了

微信掃一掃加客服

微信掃一掃加客服