Share
Using AngularJS and WebRTC to Build a Group Video Chat App on Vidyo.io - Vidyo.io
Vidyo.io Webinar: Level Therapy Builds "Mental Fitness" • July, 27, 2017 REGISTER NOW
Close

Vidyo.io Blog

Vidyo.io with Angular and WebRTCDue to the significant increase in global collaboration and network speed, video communication is on the rise. The importance of supporting video communication in your enterprise or application solution is increasing day by day.  Vidyo.io is a Communications Platform-as-a-Service (CPaaS)  that makes adding such video collaboration support extremely easy. Vidyo.io supports all major platforms on mobile, desktop and web, including JavaScript. And, since the library is written in plain JavaScript, it can be easily added to any JavaScript framework your project is written in – like AngularJS!

In this blog, I will show you how to add Vidyo to your AngularJS project. You can download the code from the Vidyo Github page here.

To get started, first you need to download the latest Vidyo.io package from the Vidyo.io download page. To get the JavaScript related files, click on “Web Package”.  This package will contain all the necessary files you will need to create your own video conferencing web application using WebRTC. It also includes the binary for a VidyoClient plugin that can be used as a browser plugin for browsers that don’t support WebRTC.

To add Vidyo to your web project, you need to include the Vidyo framework in your project. And, just like adding any other script file, you can do this by using the <script> tag in your html page.

<script src = "https://static.vidyo.io/4.1.12.8/javascript/VidyoClient/VidyoClient.js?onload=onVidyoClientLoaded&webrtc=1&plugin=0">
</script>>

In our Angular project, instead of adding it directly in our HTML page, let’s define a method called “loadVidyoClientLibrary” and add to one of our controller classes – “VideoRenderer.Controller.js”

loadVidyoClientLibrary() {
var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://static.vidyo.io/4.1.12.8/javascript/VidyoClient/VidyoClient.js?onload=onVidyoClientLoaded&webrtc=1&plugin=0';
    document.getElementsByTagName('head')[0].appendChild(script);
}

When you load the VidyoClient javaScript file as a script source, you pass a few parameters. First, the callback method, which will get called once the VidyoClient is done loading. Second, a flag indicating the framework that your browser supports WebRTC, and that it would like to use it instead of the plugin (which is set by the third parameter). Depending on the browser support you can either set “webrtc=1” or you can set “plugin=1”. For WebRTC, the Vidyo client library takes care of the all initialization code around media setup. Thus, when you call this function for the first time, the user will be prompted to grant media access (mic and camera) to the webpage.

Once the framework is ready, it needs to notify your project that it’s done and send its status. For this it needs a function to callback into your project. In Javascript, functions are first-class objects; they can be stored in variables and also be passed as arguments to functions. The VidyoClientframework utilizes this JavaScript feature to take the callback function as a parameter. In the example above I pass “onVidyoClientLoaded” as a callback method. Make sure that you define this function before you call the script src. In my project I defined this method using the <script> tag in index.html. Note that in my sample this html page is loaded before the loadVidyoClientLibrary is called.

function onVidyoClientLoaded(status) {
    switch (status.state) {
        case "READY":
            var event = new CustomEvent('vidyoclient:ready', {detail: VC});
            document.dispatchEvent(event);
            break;
        case "RETRYING":             // The library operating is temporarily paused
            break;
        case "FAILED":               // The library operating has stopped
            break;
        case "FAILEDVERSION":
            break;
        case "NOTAVAILABLE":         // The library is not available
            break;
        }        
    return true;                   // Return true to reload the plugins if not available
}

Once the VidyoClient framework successfully loads, it calls “onVidyoClientLoaded” method with the right status. From here you can bridge over to your Angular controllers. One way of doing this is by using the JavaScript “CustomEvent” API. Upon receiving the “READY” state by the VidyoClient, we create our own custom event called “vidyoclient:ready” and dispatch it.

Back in your controller class, you can listen for this event by adding –

listenEvent() {
    document.addEventListener('vidyoclient:ready', (e) => {
        this.setupVidyoClient(e.detail);
    });
}

Once this event is triggered, you can create the “VidyoConnector” object which will be used to connect to any video conference.

setupVidyoClient(VC) {
    VC.CreateVidyoConnector({
viewId: "renderer",   // HTML Div ID where the composited video will be rendered
viewStyle: "VIDYO_CONNECTORVIEWSTYLE_Default", // Visual style of the composited renderer
remoteParticipants: 16,                // Maximum number of participants
               logFileFilter: "warning all@VidyoConnector info@VidyoClient",
               logFileName:"",
               userData:""
      }).then((vidyoConnector) => {
               this.$rootScope.vidyoConnector = vidyoConnector; // Save the vidyoConnector instance for later use
      }).catch(() => {
               console.error("CreateVidyoConnector Failed");
      });
}

The first passed in the “CreateVidyoConnector” method is the “viewId”, which points to the div in the html where the video conference is rendered. In the sample project I added a videorenderer.html page, which has the div –

<div id="renderer">

The second parameter is the view style for your video conference. Here we select the default style. In the third parameter you can set the maximum number of remote participants that can be rendered on your screen. If the size of your div is small, you might consider showing just a few remote participants.

Note that you can control the size of video conference layout by controlling the size of this div. When you resize the div, the VidyoClient library will automatically adjust the size of the video tiles under it.

Once you have the VidyoConnector object, you are ready to join the call. So far you have setup the VidyoClient library and assigned a div where the library will render video. You haven’t joined any room yet. The default behavior of the library is to draw the self view in the div that you provided. To join a live video conference room, all you need is a valid token and the name of the room you want to join. You can define a “connect()” method in your controller which can be triggered on a button press.

<button ng-click="$ctrl.connect()">
 
connect() {
    vidyoConnector.Connect({
      host: "prod.vidyo.io",
      token:  <secure token>,    
      displayName: <name>,    
      resourceId: <roomId>,
      onSuccess: () => {
         // successful connection
      },
      onFailure: (reason) => {
        // failed to connect, check reason to find out why
      },
      onDisconnected: (reason) => {
        //  disconnected, this can be user triggered as well as error case
      }
    });
}

To connect to a virtual meeting room, we pass the following parameters –

  1. Host – This is typically set to “prod.vidyo.io”
  2. Token – A token is an alphanumeric string used by the vidyo.io platform to authenticate the user. The token is generated using your developer key, app ID and expiry duration. Instead of storing this developer private information on the client code, we always recommend generating the token on the backend. Samples on how to create a token are shared here. We also have several samples on the Vidyo Github page.
  3. Display Name – An alphanumeric string which will be used as your display name.
  4. ResourceID – An alphanumeric string, which identifies the videoconference room. To be in the same videoconference room, you need to have the same resourceID string value.

Demo Vidyo.io app with Angular

Adding text chat to your video app

With Vidyo.io, adding group chat feature to your project is very easy as well. Once you are connected to a room, you can send messages to all the other participants in the room and receive messages from them.

Text Chat with Angular Vidyo.io

To register for incoming chat messages, we will again use the callback mechanism discussed earlier. This time we call the “RegisterMessageEventListner” method on the VidyoConnector object to pass in our callback methods.

vidyoConnector.RegisterMessageEventListener({
    onChatMessageReceived: (participant, chatMessage) => {        
   
    }
})

When a remote participant sends a chat message to the room we are connected to, the “onChatMessageReceived” callback will get called. The first parameter in the callback method will have participant object, which will contain the information of the participant who sent the message. For example, the user ID of the participant, or the name of the participant. The second parameter will contain the alphanumeric string message. We can store these messages in an array.

this.messages = [];
 
vidyoConnector.RegisterMessageEventListener({
    onChatMessageReceived: (participant, chatMessage) => {
        this.messages.push({ id: participant.id, name: participant.name, content: chatMessage.body });
    }
})

In our HTML page, we can display these messages using the ‘ng-repeat’ directive.

<div ng-repeat="message in $ctrl.messages">
   <h5 ng-if="message.name">{{message.name}}:</h5>
       <p>{{message.content}}</p>
</div>

You can find the complete implementation of the code, along with how to install and run the app, on https://github.com/Vidyo/groupchat-angularjs.

Good luck adding video chat to your AngularJS app! Sign up for Vidyo.io for free here.