【山大会议】WebRTC基础之对等体连接

前言

在上一篇文章中,我们简单介绍了一下如何通过 WebRTC 提供的 API 实现用户设备媒体流的获取。在这篇文章中,我将着重介绍如何使用 WebRTC 搭建一个简单的 WebRTC 一对一音视频通话的 Demo。

UI 搭建

首先,我们先编写我们的 HTML 代码,搭好页面的骨架。

<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>简单的WebRTC测试</title>
		<style>
			* {
				margin: 0%;
				padding: 0%;
			}

			#btn {
				font-size: 3rem;
			}

			#room {
				width: 100vw;
				height: 100vh;
			}

			video {
				width: 480px;
				height: 270px;
				background: black;
			}
		</style>
	</head>
	<body>
		<div id="room">
			<video id="local" muted></video>
			<video id="remote"></video>
			<div>
				<textarea
					id="localSDP"
					cols="30"
					rows="10"
					placeholder="我的SDP"
					disabled
				></textarea>
				<textarea
					id="remoteSDP"
					cols="30"
					rows="10"
					placeholder="对方SDP"
					disabled
				></textarea>
				<br />
				<button id="ready">获取媒体</button>
				<button id="send" disabled>发起会话</button>
			</div>
		</div>
	</body>
</html>

我们搭建了一个简单的页面骨架,两个 <video /> 标签分别对应自己发出的视频流以及对方发送给自己的视频流。两个 <textarea /> 分别存储双方的 SDP

script 编写

在搭建好骨架后,我们来编写具体的逻辑。

获取媒体流

首先,我们需要点击 id 为 ready 的按钮,获取用户本地的音视频流。代码如下:

let localStream;
document.querySelector('#ready').onclick = () => {
	navigator.mediaDevices
		.getUserMedia({
			video: true,
			audio: true,
		})
		.then((stream) => {
			document.querySelector('#ready').disabled = true;
			localStream = stream;
			document.querySelector('#local').srcObject = localStream;
			document.querySelector('#local').play();
			document.querySelector('#send').disabled = false;
		});
};

建立本地通信信道

由于我们这个 Demo 是建立于两个不同的标签页中的,因此我们需要一个机制能在两个标签页中进行通信。在生产环境中,我们可以依赖于后端所搭建的 WebSocket 进行不同客户端间的通信,而在本地的开发环境中,我们可以选择使用 BroadcastChannel 对象来实现不同标签页之间的通信。

const bc = new BroadcastChannel('webrtc');
bc.onmessage = (e) => {
	switch (e.data.type) {
		case 'offer':
			sendAnswer(e.data.sdp);
			break;
		case 'answer':
			recvAnswer(e.data.sdp);
			break;
		case 'candidate':
			handleCandidate(e.data);
			break;
		}
};

编写对等体连接代码

下面来到我们的核心部分,对对等体的逻辑进行设计。首先,我们先定义一个 RTCPeerConnection 对象:

const peer = new RTCPeerConnection({
	// iceServers: [{ urls: 'stun:stun.stunprotocol.org:3478' }],
});

事件监听

创建好对等体连接对象后,我们为对等体连接监听两个事件。

ICE候选者

首先是监听 ICE 候选者,当监听到该事件时,我们使用 BroadcastChannel 对象将候选者数据传送给对方。

peer.onicecandidate = (evt) => {
	const message = {
		type: 'candidate',
		candidate: null,
	};
	if (evt.candidate) {
		message.candidate = evt.candidate.candidate;
		message.sdpMid = evt.candidate.sdpMid;
		message.sdpMLineIndex = evt.candidate.sdpMLineIndex;
	}
	bc.postMessage(message);
};
远程轨道改变

监听该事件可以帮助我们知晓对方是否有向对等连接添加新的流轨道,我们可以将该流轨道展示在我们的界面中。

peer.ontrack = (e) => {
	const video = document.querySelector('#remote');
	if (video.srcObject !== e.streams[0]) {
		video.srcObject = e.streams[0];
		console.log('pc received remote stream');
		video.play();
	}
};

RTCPeerConnection 生命周期

下面我们来实现整个连接的不同生命周期的处理代码。

发送 Offer

连接的建立过程是一个两次握手的机制,首先由发起方发送一条 Offer 信息。

document.querySelector('#send').onclick = sendOffer;

function sendOffer() {
	peer.createOffer({
		mandatory: {
			OfferToReceiveAudio: true, // 如果该值为false,即使本地端将发送音频数据,也不会提供远程端点发送音频数据。 如果此值为true,即使本地端不会发送音频数据,也将向远程端点发送音频数据。默认行为是仅在本地发送音频时才提供接收音频,否则不提供。
			OfferToReceiveVideo: true,
		},
	}).then((sdp) => {
		peer.setLocalDescription(sdp);
		document.querySelector('#localSDP').value = sdp.sdp;
		document.querySelector('#send').disabled = false;
		bc.postMessage({
			type: 'offer',
			sdp: sdp.sdp,
		});
	});
}
响应 Offer

接到 Offer 请求的被呼叫方,将响应此 Offer,并创建 Answer:

function sendAnswer(remoteSDP) {
	document.querySelector('#remoteSDP').value = remoteSDP;
	peer.setRemoteDescription(
		new RTCSessionDescription({
			sdp: remoteSDP,
			type: 'offer',
		})
	);
	peer.createAnswer({
		mandatory: {
			OfferToReceiveAudio: true,
			OfferToReceiveVideo: true,
		},
	}).then((sdp) => {
		peer.setLocalDescription(sdp);
		document.querySelector('#send').disabled = false;
		document.querySelector('#localSDP').value = sdp.sdp;
		bc.postMessage({
			type: 'answer',
			sdp: sdp.sdp,
		});
	});
}
接收 Answer

最后由发起方接收 Answer 并设置远程 SDP 。

function recvAnswer(remoteSDP) {
	document.querySelector('#remoteSDP').value = remoteSDP;
	peer.setRemoteDescription(
		new RTCSessionDescription({
			sdp: remoteSDP,
			type: 'answer',
		})
	);
}
候选者的处理

之前我们监听了 ICE 候选者改变的事件,并将候选者数据发送给了对方,下面我们将完善接到候选者数据后的操作。

function handleCandidate(data) {
	if (data.candidate) {
		const { candidate, sdpMLineIndex, sdpMid } = data;
		peer.addIceCandidate(data)
			.then((pc) => {
				console.log(`addIceCandidate success`);
			})
			.catch((pc, err) => {
				console.log(`failed to add ICE Candidate: ${err.toString()}`);
			});
	}
}

以上便是整个对等体连接的全过程,
示例地址:简单的WebRTC示例,打开两个标签页使用
完整的代码如下:

<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>简单的WebRTC测试</title>
		<style>
			* {
				margin: 0%;
				padding: 0%;
			}

			#btn {
				font-size: 3rem;
			}

			#room {
				width: 100vw;
				height: 100vh;
			}

			video {
				width: 480px;
				height: 270px;
				background: black;
			}
		</style>
	</head>
	<body>
		<div id="room">
			<video id="local" muted></video>
			<video id="remote"></video>
			<div>
				<textarea
					id="localSDP"
					cols="30"
					rows="10"
					placeholder="我的SDP"
					disabled
				></textarea>
				<textarea
					id="remoteSDP"
					cols="30"
					rows="10"
					placeholder="对方SDP"
					disabled
				></textarea>
				<br />
				<button id="ready">获取媒体</button>
				<button id="send" disabled>发起会话</button>
			</div>
		</div>

		<script>
			const bc = new BroadcastChannel('webrtc');
			bc.onmessage = (e) => {
				switch (e.data.type) {
					case 'offer':
						sendAnswer(e.data.sdp);
						break;
					case 'answer':
						recvAnswer(e.data.sdp);
						break;
					case 'candidate':
						handleCandidate(e.data);
						break;
				}
			};

			document.querySelector('#ready').onclick = () => {
				navigator.mediaDevices
					.getUserMedia({
						video: true,
						audio: true,
					})
					.then((stream) => {
						document.querySelector('#ready').disabled = true;
						localStream = stream;
						document.querySelector('#local').srcObject = localStream;
						document.querySelector('#local').play();
						document.querySelector('#send').disabled = false;
						document.querySelector('#send').onclick = sendOffer;
						for (const track of localStream.getTracks()) {
							peer.addTrack(track, localStream);
						}
					});
			};

			const peer = new RTCPeerConnection({
				// iceServers: [{ urls: 'stun:stun.stunprotocol.org:3478' }],
			});

			peer.onicecandidate = (evt) => {
				const message = {
					type: 'candidate',
					candidate: null,
				};
				if (evt.candidate) {
					message.candidate = evt.candidate.candidate;
					message.sdpMid = evt.candidate.sdpMid;
					message.sdpMLineIndex = evt.candidate.sdpMLineIndex;
				}
				bc.postMessage(message);
			};

			peer.ontrack = (e) => {
				const video = document.querySelector('#remote');
				if (video.srcObject !== e.streams[0]) {
					video.srcObject = e.streams[0];
					console.log('pc received remote stream');
					video.play();
				}
			};

			function sendOffer() {
				peer.createOffer({
					mandatory: {
						OfferToReceiveAudio: true, // 如果该值为false,即使本地端将发送音频数据,也不会提供远程端点发送音频数据。 如果此值为true,即使本地端不会发送音频数据,也将向远程端点发送音频数据。默认行为是仅在本地发送音频时才提供接收音频,否则不提供。
						OfferToReceiveVideo: true,
					},
				}).then((sdp) => {
					peer.setLocalDescription(sdp);
					document.querySelector('#localSDP').value = sdp.sdp;
					document.querySelector('#send').disabled = false;
					bc.postMessage({
						type: 'offer',
						sdp: sdp.sdp,
					});
				});
			}

			function sendAnswer(remoteSDP) {
				document.querySelector('#remoteSDP').value = remoteSDP;
				peer.setRemoteDescription(
					new RTCSessionDescription({
						sdp: remoteSDP,
						type: 'offer',
					})
				);
				peer.createAnswer({
					mandatory: {
						OfferToReceiveAudio: true,
						OfferToReceiveVideo: true,
					},
				}).then((sdp) => {
					peer.setLocalDescription(sdp);
					document.querySelector('#send').disabled = false;
					document.querySelector('#localSDP').value = sdp.sdp;
					bc.postMessage({
						type: 'answer',
						sdp: sdp.sdp,
					});
				});
			}

			function recvAnswer(remoteSDP) {
				document.querySelector('#remoteSDP').value = remoteSDP;
				peer.setRemoteDescription(
					new RTCSessionDescription({
						sdp: remoteSDP,
						type: 'answer',
					})
				);
			}

			function handleCandidate(data) {
				if (data.candidate) {
					const { candidate, sdpMLineIndex, sdpMid } = data;
					peer.addIceCandidate(data)
						.then((pc) => {
							console.log(`addIceCandidate success`);
						})
						.catch((pc, err) => {
							console.log(`failed to add ICE Candidate: ${err.toString()}`);
						});
				}
			}
		</script>
	</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小栗帽今天吃什么

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值