MediaStream使用webRtc多窗口传递

2024-04-18 17:20

本文主要是介绍MediaStream使用webRtc多窗口传递,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在做音视频通话,有个需求是把当前会话弄到另一个窗口单独展示,但是会话是属于主窗口的,多窗口通信目前不能直接传递对象,所以想着使用webRtc在主窗口和兄弟窗口建立连接,把主窗口建立会话得到的MediaStream传递给兄弟窗口;

主窗口界面

在这里插入图片描述

兄弟窗口界面

在这里插入图片描述

主窗口点击发送本地媒体后

在这里插入图片描述

呼叫封装_主窗口
// 主窗口WebRtc_呼叫
class CallWindowWebRtc {// 广播通道curBroadcas: BroadcastChannel;// webRtc点对点连接peerConnection: RTCPeerConnection;// 广播通道constructor({broadcastChannelName = 'yyh_text'}) {this.curBroadcas = CreateBroadcastChannel(broadcastChannelName);this.curBroadcas.onmessage = (event) => this.onMessage(event);// 处理页面刷新和关闭方法this.handlePageRefreshClose();}// 接收消息onMessage(event: any) {const msg = event.data;// 收到远端接听消息if (msg.type === 'answer') {this.handleSedRemoteSDP(msg);}if (msg.type === 'hangup') {this.hangup();}}// 发送消息_方法postMessage(msg: any) {this.curBroadcas.postMessage(msg);}// 处理页面刷新和关闭方法handlePageRefreshClose() {window.addEventListener('beforeunload', () => {this.postMessage({data: {event: 'mainPageRefresh', eventName: '主页面刷新了'}});});window.addEventListener('beforeunload', () => {this.postMessage({data: {event: 'mainPageClose', eventName: '主页面关闭了'}});});}// 处理媒体停止handleStreamStop() {if (!this.peerConnection) { return; }let localStream = this.peerConnection.getSenders();localStream.forEach((item: any) => {item.track.stop();})}// 卸载unmount() {if (this.peerConnection) {let localStream = this.peerConnection.getSenders();localStream.forEach((item: any) => {item.track.stop();})this.peerConnection.close();this.peerConnection.onicecandidate = null;this.peerConnection.ontrack = null;this.peerConnection.oniceconnectionstatechange = null;this.peerConnection = null;}if (this.curBroadcas) {this.curBroadcas.onmessage = null;this.curBroadcas = null;}}// ICE连接状态回调handleOniceconnectionstatechange(event) {// 1.检查网络配置if (this.peerConnection.iceConnectionState === 'checking') {// 发送订阅消息_给外部this.onSubscriptionMsg({event: 'iceConnectionState', code: 'checking', eventName: '检查网络配置'});// 2.ICE候选者被交换并成功建立了数据传输通道} else if (this.peerConnection.iceConnectionState === 'connected') {// 发送订阅消息_给外部this.onSubscriptionMsg({event: 'iceConnectionState', code: 'connected', eventName: 'ICE候选者被交换并成功建立了数据传输通道'});// 3.当连接被关闭或由于某种原因(如网络故障、对端关闭连接等)中断时} else if (this.peerConnection.iceConnectionState === 'disconnected') {this.hangup();this.onSubscriptionMsg({event: 'iceConnectionState', code: 'connected', eventName: 'ICE接被关闭或由于某种原因断开'});};}// 发送订阅消息给外部onSubscriptionMsg(msg: {}) {}// 创建全新的 RTCPeerConnectionhandleCreateNewPerrc() {// 停止媒体 this.handleStreamStop();// 最好每一次通话都单独创建一个RTCPeerConnection对象,防止复用导致ICE候选的收集受到之前连接的影响,导致画面延迟加载,或其它异常问题无法排查处理;this.peerConnection = new RTCPeerConnection();this.peerConnection.onicecandidate = (event) => this.onIcecandidate(event);this.peerConnection.ontrack = (event) => this.handleOnTrack(event);this.peerConnection.oniceconnectionstatechange  = (event) => this.handleOniceconnectionstatechange(event);}// 呼叫call(stream?: MediaStream) {return new Promise((resolve, reject) => {this.handleCreateNewPerrc();this.handleStreamAddPeerConnection(stream);this.handleCreateOffer().then((offer) => {// 存入本地offerthis.handleLocalDes(offer).then(() => {// 给远端发sdpthis.handleSendSDP();resolve({code: 1, message: '发送sdp给远端'});}).catch(() => {reject({code: 0, message: '存入本地offer失败'});});}).catch(() => {reject({code: 0, message: '创建offer失败'});});});}// 挂断hangup() {if (!this.peerConnection) {return;}if (this.peerConnection.signalingState === 'closed') {return;};this.postMessage({type: 'hangup'});// 停止媒体流let localStream = this.peerConnection.getSenders();localStream.forEach((item: any) => {item.track.stop();});// 关闭peerConectionthis.peerConnection.close();}// 1.获取本地媒体流getUserMediaToStream(audio: true, video: true) {return navigator.mediaDevices.getUserMedia({audio, video});}// 2.把媒体流轨道添加到 this.peerConnection 中handleStreamAddPeerConnection(stream?: MediaStream) {if (!stream) {stream = new MediaStream();}const tmpStream = new MediaStream();const audioTracks = stream.getAudioTracks();const videoTracks = stream.getVideoTracks();if (audioTracks.length) {tmpStream.addTrack(audioTracks[0]);this.peerConnection.addTrack(tmpStream.getAudioTracks()[0], tmpStream);}if (videoTracks.length) {tmpStream.addTrack(videoTracks[0]);this.peerConnection.addTrack(tmpStream.getVideoTracks()[0], tmpStream);}}// 3.创建createOfferhandleCreateOffer() {return this.peerConnection.createOffer();}// 4.设置本地SDP描述handleLocalDes(offer) {return this.peerConnection.setLocalDescription(offer);}// 5.发送SDP消息给远端handleSendSDP() {if (this.peerConnection.signalingState === 'have-local-offer') {// 使用某种方式将offer传递给窗口Bconst answerData = {type: this.peerConnection.localDescription.type,sdp: this.peerConnection.localDescription.sdp};this.curBroadcas.postMessage(answerData);}}// 6.收到远端接听_存远端SDPhandleSedRemoteSDP(msg: any) {// if (this.peerConnection.signalingState === 'stable') { return; }const answerData = msg;const answer = new RTCSessionDescription(answerData);return this.peerConnection.setRemoteDescription(answer);}// 7.用于处理ICEonIcecandidate(event) {// 如果event.candidate存在,说明有一个新的ICE候选地址产生了if (event.candidate) {  // 将ICE候选地址, 通常需要通过信令服务器发送给对端this.curBroadcas.postMessage({type: 'candidate', candidate: JSON.stringify(event.candidate)});  } else {  // 如果event.candidate不存在,则表示所有候选地址都已经收集完毕// 在某些情况下,这可能意味着ICE候选过程已完成,但并非总是如此// 因为在某些情况下,会有多轮ICE候选生成}}// 8.监听轨道赋值给video标签onTrackhandleOnTrack(event: any) {let remoteStream = event.streams[0];// 发送订阅消息_给外部this.onSubscriptionMsg({event: 'remoteStreams', eventName: '远端视频准备好了', remoteStream})}}
兄弟窗口封装
// 其它窗口WebRtc_接听
class AnswerWindowWebRtc {// 广播通道curBroadcas: BroadcastChannel;// webRtc点对点连接peerConnection: RTCPeerConnection;constructor({broadcastChannelName = 'yyh_text'}) {this.curBroadcas = CreateBroadcastChannel(broadcastChannelName);this.curBroadcas.onmessage = (event) => this.onMessage(event);this.handlePageRefreshClose();}// 接收消息onMessage(event: any) {const msg = event.data;// 收到远端SDPif (msg.type === 'offer') {this.handleCreateNewPerrc();this.onSubscriptionMsg({event: 'incomingCall', eventName: '收到新的来电', offer: msg});}// 保存这些 candidate,candidate 信息主要包括 IP 和端口号,以及所采用的协议类型等if (msg.type === 'candidate') {const candidate = new RTCIceCandidate(JSON.parse(event.data.candidate));this.peerConnection.addIceCandidate(candidate);}if (msg.type === 'hangup') {this.hangup();}}// 发送消息_方法postMessage(msg: any) {this.curBroadcas.postMessage(msg);}// 收到来电后创建全新的handleCreateNewPerrc() {// 停止媒体this.handleStreamStop();// 最好每一次通话都单独创建一个RTCPeerConnection对象,防止复用导致ICE候选的收集受到之前连接的影响,导致画面延迟加载,或其它异常问题无法排查处理;this.peerConnection = new RTCPeerConnection();this.peerConnection.ontrack = (event) => this.handleOnTrack(event);this.peerConnection.oniceconnectionstatechange  = (event) => this.handleOniceconnectionstatechange();}// 处理页面刷新和关闭方法handlePageRefreshClose() {window.addEventListener('beforeunload', () => {this.postMessage({data: {event: 'otherPageRefresh', eventName: '其它页面刷新了'}});});window.addEventListener('beforeunload', () => {this.postMessage({data: {event: 'otherPageClose', eventName: '其它页面关闭了'}});});}// 处理媒体停止handleStreamStop() {if (!this.peerConnection) { return; }let localStream = this.peerConnection.getSenders();localStream.forEach((item: any) => {item.track.stop();})}// 卸载unmount() {if (this.peerConnection) {let localStream = this.peerConnection.getSenders();localStream.forEach((item: any) => {item.track.stop();})this.peerConnection.close();this.peerConnection.onicecandidate = null;this.peerConnection.ontrack = null;this.peerConnection.oniceconnectionstatechange = null;this.peerConnection = null;}if (this.curBroadcas) {this.curBroadcas.onmessage = null;this.curBroadcas = null;}}// 挂断hangup() {if (!this.peerConnection) {return;}if (this.peerConnection.signalingState === 'closed') {return;};this.postMessage({type: 'hangup'});// 停止媒体流let localStream = this.peerConnection.getSenders();localStream.forEach((item: any) => {item.track.stop();});// 关闭peerConectionthis.peerConnection.close();}// ICE连接状态回调handleOniceconnectionstatechange() {// 1.检查网络配置if (this.peerConnection.iceConnectionState === 'checking') {// 发送订阅消息_给外部this.onSubscriptionMsg({event: 'iceConnectionState', code: 'checking', eventName: '检查网络配置'});// 2.ICE候选者被交换并成功建立了数据传输通道} else if (this.peerConnection.iceConnectionState === 'connected') {// 发送订阅消息_给外部this.onSubscriptionMsg({event: 'iceConnectionState', code: 'connected', eventName: 'ICE候选者被交换并成功建立了数据传输通道'});// 3.当连接被关闭或由于某种原因(如网络故障、对端关闭连接等)中断时} else if (this.peerConnection.iceConnectionState === 'disconnected') {this.hangup();this.onSubscriptionMsg({event: 'iceConnectionState', code: 'connected', eventName: 'ICE接被关闭或由于某种原因断开'});};}// 发送订阅消息给外部onSubscriptionMsg(msg: {}) {}// 接听answer(msg: any, stream?: MediaStream) {return new Promise((resolve, reject) => {this.handleStreamAddPeerConnection(stream);this.handleSedRemoteSDP(msg).then(() => {this.handleCreateAnswer().then((offer) => {this.handleLocalDes(offer).then(() => {this.handleSendAnswerRemoteMsg();resolve({code: 1, message: '已发送接听消息给发送端,等待ice确认'});}).catch(() => {reject({code: 0, message: '本地sdp存储失败'});});}).catch(() => {reject({code: 0, message: '创建接听offer失败'});});}).catch(() => {reject({code: 0, message: '远端sdp存储失败'});})});}// 1.获取本地媒体流getUserMediaToStream(audio: true, video: true) {return navigator.mediaDevices.getUserMedia({audio, video});}// 2.把媒体流轨道添加到 this.peerConnection 中handleStreamAddPeerConnection(stream?: MediaStream) {if (!stream) {stream = new MediaStream();}const tmpStream = new MediaStream();const audioTracks = stream.getAudioTracks();const videoTracks = stream.getVideoTracks();if (audioTracks.length) {tmpStream.addTrack(audioTracks[0]);this.peerConnection.addTrack(tmpStream.getAudioTracks()[0], tmpStream);}if (videoTracks.length) {tmpStream.addTrack(videoTracks[0]);this.peerConnection.addTrack(tmpStream.getVideoTracks()[0], tmpStream);}}// 3.收到远端邀请_存远端SDPhandleSedRemoteSDP(msg: any) {const answerData = msg;const answer = new RTCSessionDescription(answerData);return this.peerConnection.setRemoteDescription(answer);}// 4.接听handleCreateAnswer() {return this.peerConnection.createAnswer();}// 5.设置本地SDP描述handleLocalDes(offer) {return this.peerConnection.setLocalDescription(offer);}// 6.发送接听消息给远端handleSendAnswerRemoteMsg() {const answerData = {type: this.peerConnection.localDescription.type,sdp: this.peerConnection.localDescription.sdp};// 使用某种方式将answer传递回窗口Athis.curBroadcas.postMessage(answerData);}// 7.监听轨道赋值给video标签onTrackhandleOnTrack(event: any) {let remoteStream = event.streams[0];// 发送订阅消息_给外部this.onSubscriptionMsg({event: 'remoteStreams', eventName: '远端视频准备好了', remoteStream})}
}
导出方法
// 创建广播通道_建立两个窗口的广播通道,方便互发消息
function CreateBroadcastChannel(channelName: string) {return new BroadcastChannel(channelName);
};
export {CallWindowWebRtc, AnswerWindowWebRtc};
vue3主窗口使用
<template><div class="root"><h1>主窗口</h1><div class="loca_right_parent_wrap"><div class="loca_video_wrap"><div><button @click="methods.handleVideoToTracks()">发送本地视频给兄弟窗口</button></div><video id="locaVideo" autoplay controls src="./one.mp4" loop width="640" height="480" muted></video></div><div class="remote_video_wrap"><div class="tip_text">兄弟窗口视频预览 <button @click="methods.handleHangUp()">挂断</button> </div><video id="remoteVideo" autoplay controls width="640" height="480"></video></div></div></div>
</template><script lang="ts">
import {onMounted, onBeforeUnmount} from 'vue';
import {CallWindowWebRtc} from '@/Util/MultiWindowSharingStream';
let curWebRtc: any = null;
export default {setup() {const methods = {handleVideoToTracks() {if (curWebRtc) {curWebRtc.unmount && curWebRtc.unmount();}curWebRtc = new CallWindowWebRtc({});// 获取轨道const myVideo = document.getElementById('locaVideo');const myVideoStream = (myVideo as any).captureStream(30);// 呼叫curWebRtc.call(myVideoStream);// 拦截订阅消息curWebRtc.onSubscriptionMsg = (msg) => {if (msg.event && msg.event === 'remoteStreams') {const {remoteStream} = msg;const remoteRef = document.getElementById('remoteVideo');(remoteRef as HTMLVideoElement).srcObject = remoteStream;// (remoteRef as HTMLVideoElement).play();}}},handleHangUp() {if (curWebRtc) {curWebRtc.hangup && curWebRtc.hangup();}},// 处理组件卸载handleUnmount(){if (curWebRtc) {curWebRtc.unmount && curWebRtc.unmount();}}}onMounted(() => {});onBeforeUnmount(() => {methods.handleUnmount();})return {methods,}}
}
</script><style lang="scss" scoped>
.root{.loca_right_parent_wrap{display: flex;}.loca_video_wrap{box-sizing: border-box;padding: 0 5px;video{background: #000;}}.remote_video_wrap{box-sizing: border-box;padding: 0 5px;.tip_text{height: 28px;}video{background: #000;}}
}
</style>
vue3兄弟窗口使用
<template><div class="root"><h1>兄弟窗口</h1><div class="loca_right_parent_wrap"><div class="loca_video_wrap"><div class="tip_text">本地视频预览</div><video id="locaVideo" autoplay controls src="./two.mp4" loop width="640" height="480"></video></div><div class="remote_video_wrap"><div class="tip_text">主窗口视频预览 <button @click="methods.handleHangUp()">挂断</button></div><video id="remoteVideo" autoplay controls width="640" height="480"></video></div></div></div>
</template><script lang="ts">
import {onMounted, onBeforeUnmount} from 'vue';
import {AnswerWindowWebRtc} from '@/Util/MultiWindowSharingStream';
let curWebRtc: any = null;
export default {setup() {const methods = {handleVideoToTracks() {},handleInitAnswerOne() {if (curWebRtc) {curWebRtc.close && curWebRtc.close();curWebRtc = null;}curWebRtc = new AnswerWindowWebRtc({});const remoteRef = document.getElementById('remoteVideo');const myVideo = document.getElementById('locaVideo');// 拦截订阅消息curWebRtc.onSubscriptionMsg = (msg) => {// 收到远端媒体流if (msg.event && msg.event === 'remoteStreams') {const {remoteStream} = msg;const remoteRef = document.getElementById('remoteVideo');(remoteRef as HTMLVideoElement).srcObject = remoteStream;// (remoteRef as HTMLVideoElement).play();}// 收到新的来电if (msg.event && msg.event === 'incomingCall') {(remoteRef as HTMLVideoElement).srcObject = null;// 获取轨道const locaVideoStream = (myVideo as any).captureStream(30);const {offer} = msg;curWebRtc.answer(offer, locaVideoStream);}}},handleHangUp() {if (curWebRtc) {curWebRtc.hangup && curWebRtc.hangup();}},handleUnmount() {if (curWebRtc) {curWebRtc.unmount && curWebRtc.unmount();curWebRtc = null;}}}onMounted(() => {methods.handleInitAnswerOne();});onBeforeUnmount(() => {methods.handleUnmount();});return {methods}}
}
</script><style lang="scss" scoped>
.root{.loca_right_parent_wrap{display: flex;}.loca_video_wrap{box-sizing: border-box;padding: 0 5px;.tip_text{height: 28px;}video{background: #000;}}.remote_video_wrap{box-sizing: border-box;padding: 0 5px;.tip_text{height: 28px;}video{background: #000;}}
}
</style>

这篇关于MediaStream使用webRtc多窗口传递的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/915402

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti