Sample Code

The PeerConnection API is implemented according to the original WHATWG specification, although it uses ROAP signaling.

Self-view example

The "Hello World" of WebRTC:

<!doctype html>
<html>
   <head>
      <title>Simple getUserMedia() test</title>
      <script type="text/javascript">
 
      window.onload = function () {
         setTimeout(function () {
            navigator.webkitGetUserMedia("audio, video", function (stream) {
               document.getElementsByTagName("video")[0].src = window.webkitURL.createObjectURL(stream);
            });
            var pc = new PeerConnection();
         }, 2000);
      };
      </script>
   </head>
   <body>
      <video autoplay>
   </body>
</html>

Note! You need to create a PeerConnection object even though you are not going to send media to another peer. This is a limitation in the current implementation that will be fixed in a later release.

Video communication example

In the example below we are demonstrating a full voice and video communication WebRTC application, where PeerConnection signaling messages are transported from the server to client using the EventSource API. The server is implemented using the popular node.js platform.

Source code for the full application, including both EventSource and HTTP long polling versions, can be downloaded from: bowser_sample_code.zip

If you deploy the code on your own server, clients will automatically set up a WebRTC session if both A- and B-sides navigate to the same URL according to the following scheme:

http://example.com#random_token

<!doctype html>
<html>
   <head>
   <script>
   var serverConfig = "STUN 173.194.70.126:19302";
   var createId = function () { return Math.random().toString(16).substr(2); };
   var sessionId = location.hash = location.hash.substr(1) || createId();
   var userId = createId();
   var peers = {};
   var localStream;
 
   function sendSignalingMessage(peerUserId, message, callback) {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "/ctos/" + sessionId + "/" + userId + "/" + peerUserId);
      xhr.setRequestHeader("Content-Type", "text/plain");
      xhr.send(message);
      xhr.onreadystatechange = function () {
         if (xhr.readyState == 4 && callback instanceof Function)
            callback(xhr.status == 204);
      };
   };
 
   window.onload = function () {
      setTimeout(start, 500);
   };
 
   function start() {
      var PeerConn =  self.webkitDeprecatedPeerConnection || self.webkitPeerConnection;
      document.body.innerHTML = "<p>Waiting for others to join.. @" + sessionId +
            "<p>Send this link to the other participants: " + location.href;
 
      var options = {
         "audio": "yes please",
         "video": "ok then",
         "toString": function () {
            return "audio, video user";
         }
      };
      navigator.webkitGetUserMedia(options, function (stream) {
         localStream = stream;
         for (var pname in peers)
            if (peers[pname].conn)
               peers[pname].conn.addStream(localStream);
      });
 
      var es = new EventSource("/stoc/" + sessionId + "/" + userId);
      es.addEventListener("join", function (evt) {
         var peerUserId = evt.data;
         var peer = peers[peerUserId] = {};
         peer.sendQueue = [];
 
         function createPeerConnection() {
            peer.conn = new PeerConn(serverConfig, function (message) {
               function sendNextMessage(msg) {
                  sendSignalingMessage(peerUserId, msg, function () {
                     if (peer.sendQueue.length > 0)
                        sendNextMessage(peer.sendQueue.splice(0, 1));
                  });
               }
               if (!peer.sendQueue.length)
                  sendNextMessage(message);
               else
                  peer.sendQueue.append(message);
            });
 
            if (localStream)
               peer.conn.addStream(localStream);
 
            peer.conn.onaddstream = function (evt) {
               peer.video = document.createElement("video");
               peer.video.autoplay = peer.video.controls = true;
               peer.video.src = webkitURL.createObjectURL(evt.stream);
               document.body.appendChild(peer.video);
            };
 
            peer.conn.onclose = function () {
               delete document.body.removeChild(peer.video);
               delete peers[peerUserId];
            };
         };
 
         if (peerUserId > userId)
            createPeerConnection();
 
         es.addEventListener("user-" + peerUserId, function (evt) {
            if (!peer.conn)
               createPeerConnection();
            peer.conn.processSignalingMessage(evt.data);
         }, false);
 
      }, false);
 
      es.addEventListener("leave", function (evt) {
         var peer = peers[evt.data];
         if (peer && peer.conn && peer.conn.readyState != 3)
            peer.conn.close();
      }, false);
   };
 
   window.onhashchange = function (evt) {
      window.location.reload();
   };
   </script>
   </head>
<body>
</body>
</html>

Need help? Please post your questions on the Google Group.

Comments

aadya's picture

i am use this code in php application but the picture from camera is not seen in our browser pls make the help me for this. Thanks

Subscribe to Comments for &quot;&quot;