vue项目基于WebRTC实现一对一音视频通话

效果

前端代码

<template><div class="flex items-center flex-col text-center p-12 h-screen"><div class="relative h-full mb-4 fBox"><video id="localVideo"></video><video id="remoteVideo"></video><div v-if="caller && calling"><p class="mb-4 text-white">等待对方接听...</p><img style="width: 60px;" @click="hangUp" src="@/assets/guaDuang.png" alt=""></div><div v-if="called && calling"><p>收到视频邀请...</p><div class="flex"><img style="width: 60px" @click="hangUp" src="@/assets/guaDuang.png" alt=""><img style="width: 60px" @click="acceptCall" src="@/assets/jieTing.png" alt=""></div></div></div><div><button @click="callRemote" style="margin-right: 10px">发起视频</button><button @click="hangUp" style="margin-left: 10px">挂断视频</button></div></div>
</template>
<script>
import { io, Socket } from "socket.io-client";
let roomId = '001';
export default {name: 'HelloWorld',props: {msg: String},data(){return{wsSocket:null,//实例called:false,// 是否是接收方caller:false,// 是否是发起方calling:false,// 呼叫中communicating:false,// 视频通话中localVideo:null,// video标签实例,播放本人的视频remoteVideo:null,// video标签实例,播放对方的视频peer:null,localStream:null,}},methods:{// 发起方发起视频请求async callRemote(){let that = this;console.log('发起视频');that.caller = true;that.calling = true;// await getLocalStream()// 向信令服务器发送发起请求的事件await that.getLocalStream();that.wsSocket.emit('callRemote', roomId)},// 接收方同意视频请求acceptCall(){console.log('同意视频邀请');this.wsSocket.emit('acceptCall', roomId)},// 挂断视频hangUp(){this.wsSocket.emit('hangUp', roomId)},reset(){this.called = false;this.caller = false;this.calling = false;this.communicating = false;this.peer = null;this.localVideo.srcObject = null;this.remoteVideo.srcObject = null;this.localStream = undefined;console.log('挂断结束视频-------')},// 获取本地音视频流async getLocalStream(){let that = this;let obj = { audio: true, video: true };const stream = await navigator.mediaDevices.getUserMedia(obj); // 获取音视频流that.localVideo.srcObject = stream;that.localVideo.play();that.localStream = stream;return stream;}},mounted() {let that = this;that.$nextTick(()=>{that.localVideo = document.getElementById('localVideo');that.remoteVideo = document.getElementById('remoteVideo');})let sock = io('localhost:3000'); // 对应服务的端口// 连接成功sock.on('connectionSuccess', (sock) => {console.log('连接成功:');});sock.emit('joinRoom', roomId) // 前端发送加入房间事件sock.on('callRemote', (sock) => {// 如果是发送方自己收到这个事件就不用管if (!that.caller){ // 不是发送方(用户A)that.called = true; // 接听方that.calling = true; // 视频通话中}});sock.on('acceptCall',async ()=>{if (that.caller){// 用户A收到用户B同意视频的请求that.peer = new RTCPeerConnection();// 添加本地音视频流that.peer.addStream && that.peer.addStream(that.localStream);// 通过监听onicecandidate事件获取candidate信息that.peer.onicecandidate = (event) => {if (event.candidate) {console.log('用户A获取candidate信息', event.candidate);// 通过信令服务器发送candidate信息给用户Bsock.emit('sendCandidate', {roomId, candidate: event.candidate})}}// 接下来用户A和用户B就可以进行P2P通信流// 监听onaddstream来获取对方的音视频流that.peer.onaddstream = (event) => {console.log('用户A收到用户B的stream',event.stream);that.calling = false;that.communicating = true;that.remoteVideo.srcObject = event.stream;that.remoteVideo.play();}// 生成offerlet offer = await that.peer.createOffer({offerToReceiveAudio: 1,offerToReceiveVideo: 1})console.log('offer', offer);// 设置本地描述的offerawait that.peer.setLocalDescription(offer);// 通过信令服务器将offer发送给用户Bsock.emit('sendOffer', { offer, roomId })}})// 收到offersock.on('sendOffer',async (offer) => {if (that.called){ // 接收方 - 用户Bconsole.log('收到offer',offer);// 创建自己的RTCPeerConnectionthat.peer = new RTCPeerConnection();// 添加本地音视频流const stream = await that.getLocalStream();that.peer.addStream && that.peer.addStream(stream);// 通过监听onicecandidate事件获取candidate信息that.peer.onicecandidate = (event) => {if (event.candidate) {console.log('用户B获取candidate信息', event.candidate);// 通过信令服务器发送candidate信息给用户Asock.emit('sendCandidate', {roomId, candidate: event.candidate})}}// 接下来用户A和用户B就可以进行P2P通信流// 监听onaddstream来获取对方的音视频流that.peer.onaddstream = (event) => {console.log('用户B收到用户A的stream',event.stream);that.calling = false;that.communicating = true;that.remoteVideo.srcObject = event.stream;that.remoteVideo.play();}// 设置远端描述信息await that.peer.setRemoteDescription(offer);let answer = await that.peer.createAnswer();console.log('用户B生成answer',answer);await that.peer.setLocalDescription(answer);// 发送answer给信令服务器sock.emit('sendAnswer', { answer, roomId })}})// 用户A收到answersock.on('sendAnswer',async (answer) => {if (that.caller){ // 接收方 - 用户A   判断是否是发送方// console.log('用户A收到answer',answer);await that.peer.setRemoteDescription(answer);}})// 收到candidate信息sock.on('sendCandidate',async (candidate) => {console.log('收到candidate信息',candidate);// await that.peer.addIceCandidate(candidate) // 用户A和用户B分别收到candidate后,都添加到自己的peer对象上// await that.peer.addCandidate(candidate)await that.peer.addIceCandidate(candidate)})// 挂断sock.on('hangUp',()=>{that.reset()})that.wsSocket = sock;}
}
</script>

服务端代码

const socket = require('socket.io');
const http = require('http');const server = http.createServer()const io = socket(server, {cors: {origin: '*' // 配置跨域}
});io.on('connection', sock => {console.log('连接成功...')// 向客户端发送连接成功的消息sock.emit('connectionSuccess');sock.on('joinRoom',(roomId)=>{sock.join(roomId);console.log('joinRoom-房间ID:'+roomId);})// 广播有人加入到房间sock.on('callRemote',(roomId)=>{io.to(roomId).emit('callRemote')})// 广播同意接听视频sock.on('acceptCall',(roomId)=>{io.to(roomId).emit('acceptCall')})// 接收offersock.on('sendOffer',({offer,roomId})=>{io.to(roomId).emit('sendOffer',offer)})// 接收answersock.on('sendAnswer',({answer,roomId})=>{io.to(roomId).emit('sendAnswer',answer)})// 收到candidatesock.on('sendCandidate',({candidate,roomId})=>{io.to(roomId).emit('sendCandidate',candidate)})// 挂断结束视频sock.on('hangUp',(roomId)=>{io.to(roomId).emit('hangUp')})
})server.listen(3000, () => {console.log('服务器启动成功');
});

完整代码gitee地址: https://gitee.com/wade-nian/wdn-webrtc.git

参考文章:基于WebRTC实现音视频通话_npm create vite@latest webrtc-client -- --template-CSDN博客

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

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

CentOS操作

1.如何修改主机名 方法一&#xff1a; 修改命令&#xff1a;hostnamectl set-hostname 主机名 查看命令&#xff1a;hostname 方法二和方法三都是永久改变主机名&#xff0c;需要密码验证 方法二 修改命令&#xff1a;nmcli general hostname 主机名 查看命令&#xff…

普通人适合做大模型吗?过程中会发生什么潜在的挑战?

对于普通人来说&#xff0c;直接进行大模型的研发和训练可能存在一定的挑战&#xff0c;因为这通常需要以下资源和知识&#xff1a; 专业知识&#xff1a; 大模型的开发需要深入理解机器学习、深度学习、神经网络等领域的知识。 计算资源&#xff1a; 大模型的训练需要高性能的…

无处不在的AI:被科技巨头盯上的Agent智能体的崭新时代

&#x1f97d;一.Agent AI智能体 Agent AI 智能体是一种基于人工智能技术的智能代理&#xff0c;它可以自主地执行任务、与环境进行交互&#xff0c;并根据环境的变化做出决策。 OpenAI将AI Agent定义为以大语言模型&#xff08;LLM&#xff09;为大脑驱动具有自主理解、感知、…

一个账号玩遍ChatGPT/Claude-3/Midjourney 省钱又省力

当 OpenAI 的闭源 GPT-4 和 Meta 的开源 LLaMA 3 70B 模型在 Chatbot Arena Elo Score、MMLU 和 MT Benchmark 测试中表现出相当的性能时&#xff0c;选择更昂贵的专有模型&#xff08;其成本高出 58 倍&#xff09;的论据是&#xff1a; NVIDIA GPU Inference 上的运行速度比 …

新能源汽车充电站智慧充电电能服务综合解决方案

安科瑞薛瑶瑶18701709087/17343930412 ★解决方案 ✔目的地充电-EMS微电网平台 基于EMS解决方案从设备运维的角度解决本地充电的能量管理及运维问题&#xff0c;与充电管理平台打通数据&#xff0c;为企业微电网提供源、网、荷、储、充一体化解决方案。 ✔运营场站--电能服务…

教你零成本,免费使用comfyui复现remini爆火的黏土风格转绘(附完整教程)

在五一假期期间,一款名为Remini的AI照片编辑软件在小红书上迅速走红,其独特的“丑萌”黏土风格滤镜深受广大博主和用户的喜爱,引发了一波热潮,让人们玩得不亦乐乎。 Remini软件提供的这种视觉效果虽然看起来有点“丑萌”特效,然而,正是这种独树一帜的画风,使得Remini迅速…

秒翻-网页翻译最佳选择

使用方法&#xff1a; 安装“沉浸式翻译” 在扩展设置页面勾选“Beta”特性。 输入 DeepLX 现成的 API-https://api.deeplx.org/translate。

微信小程序音频怎么保存到手机

如果你想在微信小程序中收听美妙的音乐&#xff0c;又想将其保存到手机中&#xff0c;那么微信小程序音频怎么保存到手机这个问题就是你的最佳指南。 微信小程序音频下载工具我已经打包好了&#xff0c;有需要的自己下载一下 下载高手工具打包链接&#xff1a;百度网盘 请输入…

unreal engine5.3.2 Quixel bridge无法登陆

UE5系列文章目录 文章目录 UE5系列文章目录前言一、问题定位二、解决方法 前言 这几天unreal engine5.3.2 Quixel bridge无法登陆&#xff0c;输入epic 账号和密码&#xff0c;然后在输入epic发送的验证码&#xff0c;总是提示登录失败。就算是使用科学上网依然无法登录。而且…

Python——Numpy基础分析(1)

一、数据集 1.数据说明 fixed acidity 固定酸度 volatile acidity 挥发性酸度 pH 酸碱值 alcohol 酒精度数 quality 品质得分 2.部分数据展示 图 1-1部分数据展示 若需要全部数据&#xff0c;请私信作者&#xff0c;谢谢 二、导入数据——使用genfromtxt函数来读取文件…

领导想提拔你,看的从来不只是努力

谁不曾做过努力工作&#xff0c;一路升职加薪的职业规划&#xff0c;现实却给很多人泼了一盆冷水。 在大家的普遍认知里&#xff0c;北上广普遍高薪&#xff0c;月入过万就是标配。 然而在逃离北上广的热门帖子下&#xff0c;有网友发出了声音&#xff1a; “我都35了&#xff…

SpringBoot Actuator未授权访问漏洞的解决方法

1. 介绍 Spring Boot Actuator 是一个用于监控和管理 Spring Boot 应用程序的功能模块。它提供了一系列生产就绪的功能&#xff0c;帮助你了解应用程序的运行状况&#xff0c;以及在运行时对应用程序进行调整。Actuator 使用了 Spring MVC 来暴露各种 HTTP 或 JMX 端点&#x…

2024年全国五大数学建模竞赛Top榜及难度分析!推荐数维杯!!!

发现最近许多同学都陆续开始准备今年的数学建模竞赛了&#xff0c;但是随着数学建模领域越来越普及&#xff0c;影响力越来越广泛&#xff0c;参加的同学也越来越多&#xff0c;就导致有越来越多各式各样的数学建模竞赛此起彼伏出现&#xff0c;但其中有一些竞赛其实并不值得参…

Vue按照顺序实现多级弹窗(附Demo)

目录 前言1. 单个弹窗2. 多级弹窗 前言 强化各个知识点&#xff0c;以实战融合&#xff0c;以下两个Demo从实战提取 1. 单个弹窗 部署按钮框以及确定的方法即可 截图如下所示&#xff1a; 以下Demo整体逻辑如下&#xff1a; 点击“生成周月计划”按钮会触发showWeekPlanDia…

pytorch实现transformer(1): 模型介绍

文章目录 1. transformer 介绍2 Position Encoding2.1 位置编码原理2.2 代码实现3 Self-attention4 前馈层FFN5 残差连接与层归一化6 编码器和解码器结构1. transformer 介绍 Transformer 模型是由谷歌在 2017 年提出并首先应用于机器翻译的神经网络模型结构。机器翻译的目标是…

23.右值引用_c++11(左值引用的使用场景、右值引用的使用场景、左值引用和右值引用的对比、移动构造、移动赋值、右值引用完美转发)

传统的C语法中就有引用的语法&#xff0c;而C11中新增了的右值引用语法特性&#xff0c;所以从现在开始我们之前学习的引用就叫做左值引用。无论左值引用还是右值引用&#xff0c;都是给对象取别名。 4.右值引用 4.1 左值引用和右值引用 什么是左值&#xff1f;什么是左值引…

2024年常用的几款透明加密软件大全

文件透明加密软件是一种特殊类型的加密工具&#xff0c;它们能够在后台自动加密和解密文件&#xff0c;对用户来说&#xff0c;加密和解密是透明的&#xff0c;不需要额外的操作。以下是几种常见的文件透明加密软件&#xff1a; 1、Ping32&#xff1a; Ping32透明加密软件还具…

4000定制网站,因为没有案例,客户走了

接到一个要做企业站点的客户&#xff0c;属于定制开发&#xff0c;预算4000看起来是不是还行的一个订单&#xff1f; 接单第一步&#xff1a;筛客户 从客户询盘的那一刻开始就要围绕核心要素&#xff1a;预算和工期&#xff0c;凡是不符合预期的一律放掉就好了&#xff0c;没必…

Python | Leetcode Python题解之第74题搜索二维矩阵

题目&#xff1a; 题解&#xff1a; class Solution:def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:row,col len(matrix),len(matrix[0])row_l,row_r 0,row-1while row_l < row_r:m (row_lrow_r)//2if target < matrix[m][0]:row_r m-1…

[已解决]oneforAll ImportError: cannot import name ‘sre_parse‘ from ‘re‘

在使用 oneforall中&#xff0c;配置环境时出现了这个报错&#xff1a; 实际上是因为高版本python中re模块没有了sre_parse模块&#xff0c;可以修改exrex.py 代码&#xff0c;直接导入sre_parse模块&#xff0c;如下&#xff1a;