WebRTC 代码示例 [英] WebRTC code example

查看:41
本文介绍了WebRTC 代码示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 WebRTC,但似乎找不到任何有用的东西.我正在寻找示例代码.我想要一个用于信令的节点服务器和 2 个浏览器选项卡,它们将能够使用 webRTC 在它们之间传输文本.有谁知道我在哪里可以找到这方面的工作代码?

I am trying to learn WebRTC and I can’t seem to find anything helpful. I am looking for an example code. I want a node server for the signaling and 2 browser tabs that will be able to transfer text between them using webRTC. Anyone knows where can I find working code for this?

推荐答案

官方 WebRTC 示例工作,只需启动 演示 直接.然而,它们都是本地的.

The official WebRTC samples work, just launch the demos directly. They're all local however.

如果您需要节点服务器的示例,请尝试安装 emannion/webrtc-audio-video.

If you need an example with a node server, try installing emannion/webrtc-audio-video.

如果您只想要一个在两个浏览器选项卡之间进行通信的演示,请尝试这个 fiddle 没有服务器.

If you just want a demo that communicates between two browser tabs, try this fiddle with no server.

它使用我写的 localSocket hack 来模拟带有 localStorage 的网络套接字.在两个选项卡中打开它,或者更好的是在两个窗口中打开,以便您同时看到.

It uses a localSocket hack I wrote to mimmick a web socket with localStorage. Open it in two tabs, or better, two windows, so you see both.

var pc = new RTCPeerConnection();

var call = e => navigator.mediaDevices.getUserMedia({video: true, audio: true})
  .then(stream => pc.addStream(video.srcObject = stream)).catch(log);

pc.onaddstream = e => video.srcObject = e.stream;
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState);
pc.onicecandidate = e => sc.send({ice: e.candidate});
pc.onnegotiationneeded = e => pc.createOffer()
  .then(sdp => pc.setLocalDescription(sdp).then(() => sc.send({sdp}))).catch(log);

var sc = new localSocket();
sc.onmessage = e => e.data.sdp && pc.setRemoteDescription(e.data.sdp)
  .then(() => pc.signalingState == "stable" || pc.createAnswer()
    .then(sdp => pc.setLocalDescription(sdp).then(() => sc.send({sdp}))))
  .catch(log) || e.data.ice && pc.addIceCandidate(e.data.ice).catch(log);

var log = msg => div.innerHTML += "<br>" + msg;

<video id="video" height="120" width="160" autoplay></video><br>
<button onclick="call()">Call!</button><br><div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="https://rawgit.com/jan-ivar/localSocket/master/localSocket.js"></script>

(不幸的是,我的技巧在堆栈片段中不起作用,因此在两个选项卡中启动 fiddle.)

(Unfortunately, my trick doesn't work in stack snippets, so launch the fiddle in two tabs.)

哦,在 WebRTC 固化之前,请始终使用 adapter.js 以避免浏览器差异.

Oh, and always use adapter.js to avoid browser differences until WebRTC has solidified.

这篇关于WebRTC 代码示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆