vue2使用rtsp视频流接入海康威视摄像头(纯前端)

这篇具有很好参考价值的文章主要介绍了vue2使用rtsp视频流接入海康威视摄像头(纯前端)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一.获取海康威视rtsp视频流

海康威视官方的RTSP最新取流格式如下:

rtsp://用户名:密码@IP:554/Streaming/Channels/101

用户名和密码

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chromeIP就是登陆摄像头时候的IP(笔者这里IP是192.168.1.210)

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

所以笔者的rtsp流地址就是rtsp://用户名:密码@192.168.1.210:554/Streaming/Channels/101

二. 测试rtsp流是否可以播放

1.实现RTSP协议推流需要做的配置

1.1关闭萤石云的接入

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

1.2调整视频编码为H.264

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

2.安装VLC播放器

在此下载 video mediaplay官网 即(VLC)

安装完成之后 打开VLC播放器rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

在VLC播放器中打开网络串流 输入rtsp地址

成功的话我们可以看到我们所显示的摄像头rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

如果RTSP流地址正确且取流成功,VLC的界面会显示监控画面。否则会报错,报错信息写在了日志里,在[工具]>[消息]里可以看到

三.在vue2中引用rtsp视频流形式的海康摄像头

1.新建webrtcstreamer.js文件

在public文件夹下新建webrtcstreamer.js 代码贴在下方,复制粘贴即可

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<dataJson.length; i++) {
			var candidate = new RTCIceCandidate(dataJson[i]);
			
			console.log("Adding ICE candidate :" + JSON.stringify(candidate) );
			this.pc.addIceCandidate(candidate).then( () =>      { 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;
}

2.下载webrtc-streamer

资源在最上面
也可以去github上面下载:webrtc-streamer

下载完解压,打开文件夹,启动webrtc-streamer.exe

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

打开完会出现cmd一样的黑框框如下

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

如果没有启动成功可以在浏览器中输入http://127.0.0.1:8000/查看本地端口8000是否被其他应用程序占用,如果没有被占用打开窗口应该如下图所示(是可以看见自己的页面的)

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

3.封装组件video.vue(名字随意)

代码如下(但是有需要注意的地方,请看下方)

<template>
  <div id="video-contianer">
    <video
      class="video"
      ref="video"
      preload="auto"
      autoplay="autoplay"
      muted
      width="600"
      height="400"
    />
    <div
      class="mask"
      @click="handleClickVideo"
      :class="{ 'active-video-border': selectStatus }"
    ></div>
  </div>
</template>

<script>
import WebRtcStreamer from '../../public/hk/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.1.102: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()
      }
    },
  },
}
</script>

<style scoped lang="scss">
.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;
  }
}
</style>

这里要注意两个地方

第一个是rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

第二个是

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

不会查看本机端口的看这里(首先使用 Win + R打开运行 输入cmd)

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

4.使用video封装组件播放rtsp视频流

首先我们在要使用video封装组件的地方引入并且注册video组件

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

之后在页面中使用video组件 并且定义了两个变量将rtsp流传给封装的video组件

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chromertsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

效果图如下

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

5.使用此种方法播放的时候会默认带声音播放,如何取消(看这里)

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

之后声明一个方法

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

然后在created里面调用就静音了

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome

到此为止海康摄像头引入vue的方法就完美完结了

如果同学们有什么好的意见或者有什么问题可以私信我

最后祝大家事业蒸蒸日上,心想事成!

rtsp播放器 海康 vue,硬件接入,前端,javascript,vue.js,html,ajax,css,chrome文章来源地址https://www.toymoban.com/news/detail-858811.html

到了这里,关于vue2使用rtsp视频流接入海康威视摄像头(纯前端)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 海康实时监控预览视频流接入web

            我们采取的方案是后端获取视频流返回给前端,然后前端播放 根据官方文档传输对应的参数  官方接口限制:为保证数据的安全性,取流URL设有有效时间,有效时间为5分钟。 注意不同协议的限制不同,rtsp没得限制但前端播放麻烦,web端展示的话ws比较好 海康开放平

    2024年04月17日
    浏览(28)
  • web,h5海康视频接入监控视频流记录一

    项目需求,web端实现海康监控视频对接接入,需实现实时预览,云台功能,回放功能。 web端要播放视频,有三种方式,一种是装浏览器装插件,一种是装客户端exe,还有就是无插件了。浏览器装插件很早前已经行不通了,chrome42还是44之前的可以。客户端装软件,一般接受度

    2024年02月15日
    浏览(29)
  • 安防视频管理平台GB设备接入EasyCVR, 如何获取RTMP与RTSP视频流

    安防视频监控平台EasyCVR可拓展性强、视频能力灵活、部署轻快,可支持的主流标准协议有国标GB28181、RTSP/Onvif、RTMP等,以及支持厂家私有协议与SDK接入,包括海康Ehome、海大宇等设备的SDK等。平台既具备传统安防视频监控的能力,比如:视频监控直播、云端录像、云存储、录

    2024年02月15日
    浏览(27)
  • 记录对接海康威视摄像头web端实时预览:Linux+ffmpeg+nginx转换RTSP视频流(完整版实现)

            需求:web端实现海康摄像头实时预览效果         由于市面上大部分网络摄像头都支持RTSP协议视频流,web端一般无法直接使用RTSP实现视频预览,本篇使用ffmpeg对视频流进行转换,最终实现web端实时预览。         工具介绍:ffmpeg、nginx、vue         介

    2024年01月25日
    浏览(40)
  • VUE3 播放RTSP实时、回放(NVR录像机)视频流(使用WebRTC)

    1、下载webrtc-streamer,下载的最新window版本 Releases · mpromonet/webrtc-streamer · GitHub  2、解压下载包  3、webrtc-streamer.exe启动服务 (注意:这里可以通过当前文件夹下用cmd命令webrtc-streamer.exe -o这样占用cpu会很少,直接双击exe文件会占用cpu) cmd  webrtc-streamer.exe -o 启动如下图所示,

    2024年04月12日
    浏览(32)
  • 【Uni-app 引入海康h5player并接入ws视频流】

    内容简介 采用uni-app中的renderjs 引入海康H5 SDK 后端接入海康综合安防平台的开放API获取预览流 海康H5 SDK 下载地址 接入原因 因在移动端接入不管是hls flv rtsp rtmp流的播放稳定性和速度均很慢,特采用ws直连流来播放,效率很稳定性均显著提高。因采用前者流可以直接使用原生

    2024年02月11日
    浏览(60)
  • electron+vue网页直接播放RTSP视频流?

    目前大部分摄像头都支持RTSP协议,但是在浏览器限制,最新版的浏览器都不能直接播放RTSP协议,Electron 桌面应用是基于 Chromium 内核的,所以也不能直接播放RTSP,但是我们又有这个需求怎么办呢? 市场上的方案很多,有很多免费开源的,同时也有比较成熟的商业软件,丰俭

    2024年02月02日
    浏览(37)
  • 前端VUE播放RTSP、RTMP、HLS、FLV视频流的解决方案

    最近有个需求是前端在浏览器显示摄像头传回的RTSP视频流,我和后端都没做过视频流的项目,所以一步步摸索过来,方法和经验供大家参考。前端采用的技术有VUE+video.js+flv.js 从上图可以看出,RTSP流不能直接在浏览器播放,所以需要转码: RTMP的流需要在浏览器中用flash播放

    2024年02月06日
    浏览(37)
  • 视频推流测试——使用ffmpeg进行推流生成rtsp视频流

    在我们完成开发工作之后,需要通过推流的形式来验证能否正确接收视频流,并送入视频检测程序。笔者在这里使用的是业内最为常用的ffmpeg。具体方法如下。 访问ffmpeg的官网,地址为https://ffmpeg.org/download.html,按照如下途中来选择下载。 下载完成后,会得到一个zip格式的压

    2024年02月09日
    浏览(35)
  • 【音视频】如何播放rtsp视频流

    现阶段直播越来越流行,直播技术发展也越来越快。Webrtc和rtsp是比较火热的技术,而且应用也比较广泛。本文通过实践来展开介绍关于rtsp、webrtc的使用过程。 本文重点介绍如何播放rtsp视频流,通过ffplay方式以及VLC media player的方式来播放 可以参考上一篇博文:【音视频】基于

    2024年01月19日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包