webrtc终极版(一)采用RTCMultiConnection官方demo,5分钟搭建起来webrtc

webrtc终极版(一),支持https,在线部署【不是本地demo】,采用RTCMultiConnection官方demo,5分钟即可搭建成功



前言

webrtc现在简直是太火了,几乎涵盖了我们行业的方方面面,他的诱人之处在于,他是p2p通信,几乎不怎么耗费服务器流量
本文是webrtc系列的第一篇,您没看错,就是5分钟即可搭建成功,多一分钟算我输,如果您的要求比较低,甚至可以将这个直接使用起来,但是我强烈建议您不要这样做
能研究到webrtc的,一般不会是刚入门的小菜鸟,起码是技术骨干级别,所以我强烈建议您完成整个系列文章的阅读,再这个系列文章里我们将会学到以下内容

第一篇:采用RTCMultiConnection官方demo,5分钟搭建起来webrtc

第二篇:搭建自己的iceserver服务器,并用到RTCMultiConnection的demo中

第三篇:将官方RTCMultiConnection的demo部署到自己的服务器中

第四篇:如果不用第三方RTCMultiConnection,裸写一个怎么样


我们做事情,比方说webrtc这样的事情,领导可能再催着我们,再等着看效果,所以,如果我们上来就慢慢研究原理,可能两三天过去了,也没有搞定,这样我们心里就会发慌,工作内容总不能一直写研究webrtc吧,所以上来先完成一个demo,并能正常运行,就显得非常重要了。

一、webrtc是什么?

能看到这篇文章的,相信几乎没有不知道什么是webrtc的了,但是作为文章的重要组成部分,还是需要介绍下什么是webrtc。

它(WebRTC)允许网络应用或者站点,在不借助中间媒介的情况下,建立浏览器之间点对点(Peer-to-Peer)的连接,实现视频流和(或)音频流或者其他任意数据的传输

这是 MDN 上对 WebRTC 的描述,初次接触时无法理解 WebRTC 为什么要和 WebSocket 搭配,明明说的很清楚 不借助中间媒介 ,那 WebSocket 充当的是什么角色?整个 WebRTC 通话建立的流程又是怎样的?

上面的问题是个大的话题,原理介绍我准备放到第四篇章进行,本篇文章,我们就只有一个目的,那就是5分钟搭建一个webrtc,enjoy it!

二、搭建demo步骤

1.代码内容

啥都不说了,直接上代码:

<!DOCTYPETYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Video Conference</title>
</head>
<body>
<button id="btn-open-room">Open Room</button>
<button id="btn-join-room">Join Room</button>
  <!-- Include RTCMultiConnectionClient.js -->
<script src="https://muazkhan.com:9001/dist/RTCMultiConnection.min.js"></script>
<script src="https://muazkhan.com:9001/socket.io/socket.io.js"></script>
<script>
var connection = new RTCMultiConnection();

// this line is VERY_important
connection.socketURL = 'https://muazkhan.com:9001/';

// all below lines are optional; however recommended.

connection.session = {
    audio: true,
    video: true
};

connection.sdpConstraints.mandatory = {
    OfferToReceiveAudio: true,
    OfferToReceiveVideo: true
};

connection.onstream = function(event) {
    debugger;
    document.body.appendChild( event.mediaElement );
};


var predefinedRoomId = 'testroom';

// first step, ignore default STUN+TURN servers
connection.iceServers = [];
connection.iceServers.push({
    urls: 'stun:muazkhan.com:3478',
    credential: 'muazkh',
    username: 'hkzaum'
});
connection.iceServers.push({
    urls: 'turns:muazkhan.com:5349',
    credential: 'muazkh',
    username: 'hkzaum'
});
connection.iceServers.push({
    urls: 'turn:muazkhan.com:3478',
    credential: 'muazkh',
    username: 'hkzaum'
});

document.getElementById('btn-open-room').onclick = function() {
    this.disabled = true;
    connection.open( predefinedRoomId );
};

document.getElementById('btn-join-room').onclick = function() {
    this.disabled = true;
    connection.join( predefinedRoomId );
};
</script>
</body>
</html>

2.运行效果

第一个界面:运行页面后的初始界面
图1
第二个界面,点击open room,并同意音视频采集请求
点击open room按钮的效果

第三个界面:点击jon room按钮的效果
点击join room按钮的效果

第四个界面:多人点击join room按钮的效果
多人链接的效果

总结

以上html,您可以再本地直接打开运行,本地打开,那就只能内网测试了,同时,您也可以把这个html放到公网上,注意是必须https,否则浏览器会阻止音视频的打开

本文是webrtc的开篇,是不是感觉非常的轻松,并且对webrtc充满信心了呢?这个第三方的组件,是支持多人音视频聊天的,非常的强大,后续几篇我们会深入讨论。

同时也欢迎您关注爱自律官方微信公众号,同时体验爱自律小程序的使用,让我们一起爱上自律,拥抱自由吧。

很抱歉,我作为一个AI语言模型,并没有能力编写和展示实时WebRTC demo。但我可以提供一些基本的代码来启动一个简单的WebRTC连接。 1. 首先,需要创建两个HTML文件:index.html和remote.html。index.html是发送方,remote.html是接收方。 2. 在index.html中,需要创建一个video标签和两个button标签,一个用于开始连接,另一个用于断开连接。 ```html <video id="localVideo"></video> <button id="startButton">Start Connection</button> <button id="stopButton">Stop Connection</button> ``` 3. 在remote.html中,需要创建一个video标签来显示接收到的视频流。 ```html <video id="remoteVideo"></video> ``` 4. 在JavaScript中,需要使用WebRTC API来建立连接。首先,需要创建一个RTCPeerConnection对象。 ```javascript const localVideo = document.querySelector('#localVideo'); const remoteVideo = document.querySelector('#remoteVideo'); const startButton = document.querySelector('#startButton'); const stopButton = document.querySelector('#stopButton'); let localStream; let pc1; let pc2; const offerOptions = { offerToReceiveVideo: 1, }; startButton.addEventListener('click', start); stopButton.addEventListener('click', stop); async function start() { try { localStream = await navigator.mediaDevices.getUserMedia({ video: true }); localVideo.srcObject = localStream; } catch (e) { console.error('getUserMedia() error:', e); return; } pc1 = new RTCPeerConnection(); pc2 = new RTCPeerConnection(); pc1.addEventListener('icecandidate', e => onIceCandidate(pc1, pc2, e)); pc2.addEventListener('icecandidate', e => onIceCandidate(pc2, pc1, e)); pc2.addEventListener('track', gotRemoteStream); localStream.getTracks().forEach(track => pc1.addTrack(track, localStream)); try { const offer = await pc1.createOffer(offerOptions); await onCreateOfferSuccess(offer, pc1, pc2); } catch (e) { onCreateSessionDescriptionError(e); } } function onCreateSessionDescriptionError(error) { console.error(`Failed to create session description: ${error.toString()}`); } async function onCreateOfferSuccess(desc, pc1, pc2) { console.log(`Offer from pc1\n${desc.sdp}`); await pc1.setLocalDescription(desc); await pc2.setRemoteDescription(desc); try { const answer = await pc2.createAnswer(); await onCreateAnswerSuccess(answer, pc1, pc2); } catch (e) { onCreateSessionDescriptionError(e); } } async function onCreateAnswerSuccess(desc, pc1, pc2) { console.log(`Answer from pc2:\n${desc.sdp}`); await pc2.setLocalDescription(desc); await pc1.setRemoteDescription(desc); } function onIceCandidate(pc, otherPc, event) { if (event.candidate) { otherPc.addIceCandidate(event.candidate) .then(() => { console.log('addIceCandidate success'); }).catch((err) => { console.error(`addIceCandidate error: ${err}`); }); } } function gotRemoteStream(e) { if (remoteVideo.srcObject !== e.streams[0]) { remoteVideo.srcObject = e.streams[0]; console.log('received remote stream'); } } function stop() { pc1.close(); pc2.close(); pc1 = null; pc2 = null; startButton.disabled = false; stopButton.disabled = true; } ``` 5. 最后,在本地运行index.html和remote.html文件,点击“Start Connection”按钮,即可建立WebRTC连接并开始传输视频流。 以上只是一个简单的WebRTC连接示例,实际中可能需要更多的代码和调试。同时,需要注意WebRTC连接需要在HTTPS环境下运行,否则可能会出现安全问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值