Real Time Communication with WebRTC

Introduction

WebRTC is an open source project to enable realtime communication of audio, video and data in Web and native apps.

WebRTC can be used in Firefox, Opera and in Chrome on desktop and Android. It’s also available for native apps on iOS and Android.

Signaling

WebRTC uses RTCPeerConnection to communicate streaming data between browsers, but also needs a mechanism to coordinate communication and to send control messages, a process known as signaling.

STUN and TURN

WebRTC is designed to work peer-to-peer, so users can connect by the most direct route possible.

The WebRTC APIs use STUN servers to get the IP address of your computer, and TURN servers to function as relay servers in case peer-to-peer communication fails.

Security

Encryption is mandatory for all WebRTC components, and its JavaScript APIs can only be used from secure origin(HTTPS or localhost). Signaling mechanisms aren’t defined by WebRTC standards, so it’s up to you make sure to use secure protocols.

Stream Video from Webcam

Add a video element and a script element to index.html.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Realtime communication with WebRTC</title>
    <link rel="stylesheet" href="css/main.css" />
  </head>
  <body>
    <h1>Realtime communication with WebRTC.</h1>
    <video autoplay playsinline></video>
    <script src="js/main.js"></script>
  </body>
</html>

Add the following to main.js in your js folder.

"use strict";

const mediaStreamConstrains = {
  video: true,
  audio: true
};

const hdConstraints = {
  video: {
    width: {
      min: 1280
    },
    height: {
      min: 720
    }
  },
  audio: true
};

// Video element where stream will be placed.
const localVideo = document.querySelector("video");

// Local stream that will be reproduced on the video.
let localStream;

// Handles success by adding the MediaStream to the video element
function gotLocalMediaStream(mediaStream) {
  localStream = mediaStream;
  localVideo.srcObject = mediaStream;
}

// Handles error by logging a message to the console with the error
function handleLocalMediaStreamError(error) {
  console.log("navigator.getUserMedia error: ", error);
}

// Initializes media stream.
navigator.mediaDevices
  .getUserMedia(hdConstraints)
  .then(gotLocalMediaStream)
  .catch(handleLocalMediaStreamError);

Note: Cover Picture