WebRTC code example

2019-09-20 04:39发布

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?

1条回答
放荡不羁爱自由
2楼-- · 2019-09-20 05:10

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

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

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

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>

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

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

查看更多
登录 后发表回答