【vue2】前端如何播放rtsp 视频流,拿到rtsp视频流地址如何处理,海康视频rtsp h264 如何播放

文章目录

    • 测试
    • 以vue2 为例
      • 新建 webrtcstreamer.js
      • 下载webrtc-streamer
      • video.vue
      • 页面中调用

最近在写vue2 项目其中有个需求是实时播放摄像头的视频,摄像头是 海康的设备,搞了很长时间终于监控视频出来了,记录一下,放置下次遇到。文章有点长,略显啰嗦请耐心看完。

测试

测试?测试什么?测试rtsp视频流能不能播放。

video mediaplay官网 即(VLC)

下载、安装完VLC后,打开VLC 点击媒体 -> 打开网络串流

在这里插入图片描述
将rtsp地址粘贴进去

在这里插入图片描述

不能播放的话,rtsp视频流地址有问题。
注意:视频可以播放也要查看视频的格式,如下

右击视频选择工具->编解码器信息

在这里插入图片描述

如果编解码是H264的,那么我的这种方法可以。如果是H265或者其他的话就要登录海康后台修改一下

在这里插入图片描述

以vue2 为例

新建 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;
}

下载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 地址 就是了

<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/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();
      }
    },
  },
};
</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>

页面中调用

在页面中引入video.vue,并注册。将rtsp视频地址传过去就好了,要显示几个视频就调用几次

在这里插入图片描述

回到页面看,rtsp视频已经可以播放了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/155495.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

2023年首届天府杯数学建模国际大赛问题A思路详解与参考代码:大地测量数据中异常现象的特征和识别

地球变形观测是固体潮汐曲线分析和地震前体研究的重要手段&#xff0c;也是地球观测技术的重要组成部分。基于各种精密科学仪器的变形观测点主要集中在洞穴、地下井等易的自然灾害&#xff08;雷暴、强降雨、降雪等&#xff09;&#xff0c;人工维护、人工爆破等外部条件&#…

类似于推箱子的小游戏 寻找 最短路径

实现效果如下 类似 推箱子小游戏 的变种 C/C版本 BFS最短路径 黑色代表墙壁 不能越过 蓝色代表HOME点 灰色代表要找的小箱子 绿色代表路径 最终目标是将灰色的小箱子移动到蓝色的HOME点 需要两次搜索 第一次是 出发点到灰色小箱子 第二次是灰色小箱子到蓝色HOME点 BF…

IntelliJ IDE 插件开发 |(一)快速入门

前言 IntelliJ IDEA 作为 Java 开发的首选 IDE&#xff0c;其强大、方便之处不必多说。不过&#xff0c;由于个人或者团队的个性化需求&#xff0c;我们或多或少会想对其功能进行拓展&#xff0c;这时就需要开发插件&#xff08;在 IntelliJ 平台下的所有 IDE 均可运行&#x…

QtCreator13源码windows编译

1.下载QtCreator13源码: https://download.qt.io/snapshots/qtcreator/13.0/13.0.0-beta1/installer_source/latest/qt-creator-opensource-src-13.0.0-beta1.zip 2.下载并安装llvm Release LLVM 17.0.5 llvm/llvm-project GitHub 3.系统 要求&#xff1a; Windows 10 (64…

设计模式-代理模式-笔记

动机&#xff08;Motivation&#xff09; 在面向对象系统中&#xff0c;有些对象由于某种原因&#xff08;比如对象创建的开销很大&#xff0c;或者某些操作需要安全控制&#xff0c;或者需要远程外的访问等&#xff09;&#xff0c;直接访问会给使用者、或者系统结构带来很多…

Python ... takes 0 positional arguments but 1 was given

最近&#xff0c;博主在学习python时遇到这么个报错&#xff0c; 系统&#xff1a;windows10 开发环境&#xff1a;VS Code Python版本&#xff1a;3.12 错误重现&#xff1a; class Dog:def __init__(self):passdef eatSomething(self):self.eatBone()def eatBone():prin…

python趣味编程-5分钟实现一个Flappy Bird游戏(含源码、步骤讲解)

Python 中的 Flappy Bird 游戏可以免费下载开源代码,它是为想要学习 Python 的初学者创建的。 该项目系统使用了 Pygame 和 Random 模块。 Pygame 是一组跨平台的 Python 模块,专为编写视频游戏而设计。 Python 中的 Flappy Bird 代码 – 项目信息 项目名称:Python 中的 Fl…

pipeline jenkins流水线

Pipeline 是 Jenkins 中一种灵活且强大的工作流机制&#xff0c;它允许您以代码的形式来定义和管理持续集成和持续交付的流程。 Pipeline 的作用主要体现在以下几个方面&#xff1a; 可编排的构建流程&#xff1a;使用 Pipeline&#xff0c;您可以将一个或多个阶段&#xff08…

腾讯云服务器租用价格,腾讯云服务器租用价格多少钱一年?

腾讯云服务器租用价格&#xff0c;腾讯云服务器租用价格多少钱一年&#xff1f;腾讯云服务器有优惠活动&#xff0c;现在租用只需要88元/年&#xff01;腾讯云服务器优惠购买入口&#xff1a;https://1111.mian100.cn 随着互联网的发展&#xff0c;越来越多的人开始选择将自己…

解决:Error: Missing binding xxxxx\node_modules\node-sass\vendor\win32-x64-83\

一、具体报错 二、报错原因 这个错误是由于缺少 node-sass 模块的绑定文件引起的。 三、导致原因 3.1、环境发生了变化 3.2、安装过程出现问题 四、解决方法步骤&#xff1a; 4.1、重新构建 node-sass 模块 npm rebuild node-sass 4.2、清除缓存并重新安装依赖 npm c…

【数据结构】【版本1.4】【线性时代】——公平队列

目录 引言 队列的概念与结构 队列的实现 定义 初始化 销毁 入队 判断队列是否为空 出队 获取队头元素 获取队尾元素 检测队列中有效元素个数 元素访问 源代码 queue.h queue.c test.c 个人专栏&#xff1a;《数据结构世界》 引言 数据结构世界遇到栈后&a…

【观察】OpenHarmony:技术先进“创新局”,持续创新“谋新篇”

毫无疑问&#xff0c;开源作为今天整个软件产业的创新“原动力”&#xff0c;目前在软件产业发展中的重要性愈加凸显。根据Linux基金会的统计&#xff0c;现在全球软件产业中有70%以上的代码来源于开源软件。 从这个角度来看&#xff0c;开源技术已逐渐成为推动企业数字化转型和…

【Gitpod】云部署Stable Diffusion并且可以本地访问

文章目录 前言项目部署 项目启动参考文献 前言 本文介绍如何使用 Gitpod 部署 Stable Diffusion web UI。Gitpod 是一个基于云的开发环境&#xff0c;通过与 GitHub 集成&#xff0c;可以在浏览器中轻松进行代码开发和部署&#xff1b;Stable Diffusion 是 GitHub 上面的开源 …

【电路笔记】-脉冲宽度调制(PWM)与电机转速控制

脉冲宽度调制&#xff08;PWM&#xff09;与电机转速控制 文章目录 脉冲宽度调制&#xff08;PWM&#xff09;与电机转速控制1、概述2、电机转速控制3、PWM产生 有许多不同的方法来控制直流电机的速度&#xff0c;但一种非常简单且容易的方法是使用脉冲宽度调制&#xff08;PWM…

【AI视野·今日Robot 机器人论文速览 第六十二期】Wed, 25 Oct 2023

AI视野今日CS.Robotics 机器人学论文速览 Wed, 25 Oct 2023 Totally 25 papers &#x1f449;上期速览✈更多精彩请移步主页 Daily Robotics Papers EquivAct: SIM(3)-Equivariant Visuomotor Policies beyond Rigid Object Manipulation Authors Jingyun Yang, Congyue Deng,…

ES Kibana 安装

ES & Kibana 本文基于Docker安装部署使用 Kibana的版本和ElasticSearch的版本&#xff0c;以及IK分词器的版本一一对应 Kibana 安装 安装Kibana # 创建网络 [rootiZ2zeg7mctvft5renx1qvbZ ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway …

Alibaba Nacos注册中心实战

为什么需要注册中心 思考&#xff1a;网络请求&#xff0c;如果服务提供者发生变动&#xff0c;服务调用者如何感知服务提供者的ip和端口变化&#xff1f; // 微服务之间通过RestTemplate调用&#xff0c;ip:port写死&#xff0c;如果ip或者port变化呢&#xff1f; String ur…

[PHP]写个简单的分页静态接口用宝塔部署到Nginx

使用get方式传入page和pageSize参数&#xff0c;接口根据参数进行分页处理。 1.创建一个 PHP 文件 例如 city.php&#xff0c;用于定义接口和返回 JSON 数据。 2.在 city.php 文件中编写接口 <?php// 设置响应内容为 JSON 格式 header(Content-Type: application/json);…

EasyCVR视频监控+AI智能分析网关如何助力木材厂安全生产?

旭帆科技有很多工厂的视频监管方案&#xff0c;小编也经常分享出来供大家参考。近期&#xff0c;又有伙伴后台私信我们想要关于木材厂的方案。针对木材厂的生产过程与特性以及安全风险等&#xff0c;我们来分享一下相关的监管方案&#xff1a; 1&#xff09;温湿度监测&#xf…

Skywalking流程分析_9(JDK类库中增强流程)

前言 之前的文章详细介绍了关于非JDK类库的静态方法、构造方法、实例方法的增强拦截流程&#xff0c;本文会详细分析JDK类库中的类是如何被增强拦截的 回到最开始的SkyWalkingAgent#premain try {/** 里面有个重点逻辑 把一些类注入到Boostrap类加载器中 为了解决Bootstrap类…
最新文章