loading

WebRTC, so hot right now. If you haven’t heard of it, WebRTC (Web Realtime Communications) is an API that enables peer-to-peer video, audio, and data communication in a web browser with no plugins, frameworks, or applications required.

In this tutorial, we’ll start by building a very simple video chat application that only requires around 20 lines of JavaScript. Our application will enable users to enter a username and call another user between browsers. In our next part, we’ll add some cool features to bolster our WebRTC video app.

Check out the live WebRTC video chat demo here, open up two windows, and watch it in action!

And if you want to check out the project code for the tutorial series, it’s available here.

And the project code for this specific project here.

That’s right! Let’s get to it.

Step 1: Quick Note on Testing and Debugging

WebRTC is widely adopted by popular browsers such as Chrome and Firefox, but there are many browsers on which certain features will not work. See a list of supported browsers here.

If you try to openfile://your-webrtc-project in your browser, you will likely run into Cross-Origin Resource Sharing (CORS) errors since the browser will block your requests to use video and microphone features.

To test your code you have a few options. You can upload your files to a web server, like Github Pages if you prefer. However, to keep development local, I recommend you setup a simple server using Python. To do this, open your terminal and change directories into your current project and depending on your version of Python, run one of the following modules.

cd <project-dir>

# Python 2
python -m SimpleHTTPServer <port-no>

# Python 3
python -m http.server <port-no>

For example, I run Python2.7 and the command I use is python -m SimpleHTTPServer 8001. Now I can go to http://localhost:8001/index.html to debug my app. Try making an index.html with anything in it and serve it on localhost before you continue.

Step 2: The HTML5 Backbone

For the sake of the demo, let’s keep the HTML short and simple. First we need a div to house our videos. Then, all we really need to start off with is a login field so you can specify your name and a call field so you can dial someone.

<div id="vid-box"></div>
<form name="loginForm" id="login" action="#" onsubmit="return login(this);">
    <input type="text" name="username" id="username" placeholder="Pick a username!" />
    <input type="submit" name="login_submit" value="Log In">
</form>
<form name="callForm" id="call" action="#" onsubmit="return makeCall(this);">
 <input type="text" name="number" placeholder="Enter user to dial!" />
 <input type="submit" value="Call"/>
</form>

This should leave you with an elaborate, well styled HTML backbone that looks something like the image header to this step.

Step 3: The JavaScript Imports

There are three libraries that you will need to include to make WebRTC operations much easier:

  1. Include jQuery to make modifying DOM elements a breeze.
  2. Include the PubNub JavaScript SDK to facilitate the WebRTC signaling (more on signaling at the bottom of this blog post).
  3. Include the PubNub WebRTC SDK to make placing phone calls as simple as calling the dial(number)function.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.pubnub.com/pubnub-3.7.14.min.js"></script>
<script src="http://cdn.pubnub.com/webrtc/webrtc.js"></script>

Now we’re ready to write our calling functions for login and makeCall.

Step 4: Preparing to Receive Calls

In order to start facilitating video calls, you will need a publish and subscribe key. To get your pub/sub keys, you’ll first need to sign up for a PubNub account. Once you sign up, you can find your unique PubNub keys in the PubNub Developer Dashboard. The free Sandbox tier should give you all the bandwidth you need to build and test your WebRTC application.

First, lets use JavaScript to find our video holder, where other callers faces will go.

var video_out = document.getElementById("vid-box");

Next, we’ll implement the login function. This function will set up the phone using the username they provided as a UUID.

function login(form) {
     var phone = window.phone = PHONE({
     number        : form.username.value || "Anonymous", // listen on username line else Anonymous
     publish_key   : 'your_pub_key',
     subscribe_key : 'your_sub_key',
 }); 
 phone.ready(function(){ form.username.style.background="#55ff5b"; });
 phone.receive(function(session){
     session.connected(function(session) { video_out.appendChild(session.video); });
     session.ended(function(session) { video_out.innerHTML=''; });
 });
 return false;  // So the form does not submit.
}

You can see we use the username as the phone’s number, and instantiate PubNub using your own publish and subscribe keys. The next function, phone.ready, allows you to define a callback for when the phone is ready to place a call. I simply change the username input’s background to green, but you can tailor this to your needs.

The phone.receive function allows you to define a callback that takes a session as a parameter for when a call event occurs, whether that be a new call, a call hangup, or for losing service, you attach those event handlers to the sessions in phone.receive.

I defined session.connected which is invoked after receiving a phone call, and when you are ready to begin video chatting. I simply appended the session’s stream to our video div.

Then, I define session.ended which is called after invoking phone.hangup. This is where you place end-call logic. I simply clear the video holder’s innerHTML.

Step 5: Making Calls

We now have a our WebRTC video app ready to receive a call, so it is time to create a makeCall function.

function makeCall(form){
        if (!window.phone) alert("Login First!");
	else phone.dial(form.number.value);
	return false;
}

If window.phone is undefined, we cannot place a call. This will happen if the user did not log in first. If it exists, we use the phone.dial function which takes a number and an optional list of servers to place a call.

And that is it! You now have a simple WebRTC video chat app. Fire up your python server and go test your app on localhost!

In our next two parts, we walkthrough how to add a number of additional features to your WebRTC video chat application, including: make/end Calls, thumbnail streams, mute call, pause video, and group chatting. We’ll also walk through how to create live embeddable streaming content (ie. how to build Periscope with WebRTC!).

Step 6: Why PubNub?

WebRTC is not a standalone API, it needs a signaling service to coordinate communication. Metadata needs to be sent between callers before a connection can be established.

This metadata includes things such as:

  • Session control messages to open and close connections
  • Error messages
  • Codecs/Codec settings, bandwidth and media types
  • Keys to establish a secure connection
  • Network data such as host IP and port

Once signaling has taken place, video/audio/data is streamed directly between clients, using WebRTC’s PeerConnection API. This peer-to-peer direct connection allows you to stream high-bandwidth robust data, like video.

PubNub makes this signaling incredibly simple, and then gives you the power to do so much more with your WebRTC applications.

Step 7: Want to Learn More?

Good, that never-ending quest for knowledge will get you far in life. I hope you enjoyed this tutorial, but this is just the beginning. WebRTC is a powerful tool that you'll hear a lot more of in the future, and a great skill to have. When you cast your browser tab to a Chromecast, that's WebRTC and a screen share. Check out some of my other WebRTC posts:

Finally, here are some other resources PubNub offers on WebRTC:

Stay tuned, more content around WebRTC is still on the way!

About This Instructable

7,036views

20favorites

Bio: I'm just happy to be here.
More by KAGleason:WebRTC Video Chat in 20 Lines of JavaScript  IoT: DIY Hue Light 
Add instructable to: