QuickStart Guide

Let's build your first video chat app in HTML, CSS and Javascript

Setting things up

In order to connect to the ApiRTC services, you need an API key.

To find out your API key:

  1. Register and log into your ApiRTC account on https://cloud.apirtc.com.

  2. Grab it and keep it aside, we will soon use this key.

  3. Enter 127.0.0.1 (for the purpose of this tutorial) or the targeted application domain in the list of authorized domains. You may use wildcards as *.mydomain.com.

This project is a simple Web Application consisting of an HTML file, a Javascript file and a CSS file.

Before delving into the code, you need to create a project directory ( quickstart_apirtcjs/ for example) for your application.

This folder will eventually look as follows:

quickstart_apirtcjs/
├── css
   └── app.css
├── index.html
└── js
    └── app.js
Command line instructions
mkdir css
mkdir js
touch index.html
touch css/app.css
touch js/app.js

Now, let's build the app!

Create some placeholders for video streams

ApiRTC is to be used in a brower. It will use the DOM Elements to display the video streams.

In the index.html :

  • Create a basic HTML markup structure

  • Reference app.css and the latest version of the ApiRTC library

  • Reference the app.js javascript file at the end just before the </body> closing tag

  • Add 2 div elements identified as remote (that will contains all the video streams from remote participant) and local (that will contains your own camera display)

 <!DOCTYPE html>
 <html>
    <head>
      <title>ApiRTC Quickstart</title>
      <link rel="stylesheet" href="css/app.css"/>
      <script type="text/javascript" src="https://cdn.apirtc.com/apiRTC/apiRTC-latest.min.js"></script>
    </head>
    <body>
        <div id="conference">
            <div id="remote"></div>
            <video id="local" autoplay="true" muted="true" width="320" height="240" ></video>
        </div>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

Connect to the ApiRTC platform

Let's open the app.js file to develop the scripting part.

The first step is to create a UserAgent to connect to the ApiRTC server and manage media streams.

var API_KEY = '#INSERT_YOUR_APIKEY_HERE#'; 

var userAgent = new apiRTC.UserAgent({ uri: 'apiKey:' + API_KEY })
let conversation = undefined

userAgent.register({
    cloudUrl: 'https://cloud.apirtc.com'
}).then( (session) => {
    alert("You're connected, well done!")
});

You need to replace #INSERT_YOUR_APIKEY_HERE# by your ApiRTC key. Refer to the **** Get your ApiRTC key and authorize your domain section if you don’t already have your key available.

Launch a webserver pointing to index.html, open your browser and to see the magic!

Launch a webserver
npx http-server

Then navigate to http://127.0.0.1:8080.

See other connection mode in the Authenticationsection.

Create an ApiRTC conversation and publish your local video

Now that you are connected to the ApiRTC plaform, we will:

1. Retrieve a Conversation through its convarsationName (which is a simple string)

2. Retrieve the local camera video stream and local audio stream

3. Display the local video stream in the HTML page

4. Join the Conversation

5. Publish our local camera video stream into the Conversation to shared across all the participants.

Replace the userAgent.register call instruction in app.js by the code below:

userAgent.register({
    cloudUrl: 'https://cloud.apirtc.com'
}).then((session) => {

    //Prepare connection to conversation
    conversation = session.getOrCreateConversation('quickstart_conversation')
    
    // Define the way the local stream will be configured
    let streamOptions = {
        constraints: {
            audio: true,
            video: true
        }
    }

    //Get the stream for the local camera
    userAgent.createStream(streamOptions).then(function (stream) {
        
        //Display the stream (audio+video) in the <video> element with id 'local'
        stream.attachToElement(document.getElementById('local'))
        
        //Join the conversation
        conversation.join().then(() => {
        
            //Publish the local stream in the conversation
            conversation.publish(stream)
        });
    });
});

Reload the web page in your browser.

You should be prompted to allow mic and camera use.

Click on the "Allow" button.

Note that you should read Subscribed to XXXXXXXXXXXXXXXXX in your browser console.

Subscribe to remote streams

Each time a new participant publishes their stream to the Conversation, you want to display it in your webpage.

3 events are triggered by the Conversation object to help us with it:

  • streamListChanged : when any stream is added or remove to the Conversation's stream list, or when one of the stream's attributes changes.

  • streamAdded : triggered when a new stream is added to the Conversation (only by streams you are subscribed to)

  • streamRemoved triggered when a stream is removed from the Conversation (only by streams you are subscribed to)

To get it right with this, you need to:

  1. Subscribe to new streams when the streamListChanged is triggered

  2. Add a new participant's video to the HTML page when streamAdded is triggered

  3. Remove a participant's video from the HTML page when streamRemoved is triggered

//Any time the streamListChanged is triggered
    conversation.on('streamListChanged', (streamInfo) => {

        // when a new stream is added AND the added stream is not 
        if (streamInfo.listEventType === 'added' && streamInfo.isRemote === true) {

            //Subscribe to the new stream's events (triggered by the conversation object)
            conversation.subscribeToMedia(streamInfo.streamId).then((stream) => {
                console.log("Subscribed to " + stream.streamId)
            })
        }
    });

    //Any time a (subscribed) stream is added to the conversation
    conversation.on('streamAdded', (stream) => {
        
        //Add a video element in the 'remote' div element,  with the streamId in its id attribute
        stream.addInDiv('remote', 'remote-media-' + stream.streamId, {}, false)
    
    });

    //Any time a (subscribed) stream is removed from the conversation
    conversation.on('streamRemoved', (stream) => {
        
        //Remove a video element with the streamId in its id attribute
        stream.removeFromDiv('remote', 'remote-media-' + stream.streamId)
    });

If your speakers and microphone are opened, you will get some shrieking feedback sound. Turn off your microphone and all should be fine.

Go deeper into the ApiRTC model

Read the ApiRTC Javascript Reference documentation pages:

Final touch, get some style

Let's beautiful your first video app with some CSS styling. Edit the app.css file and add the following code:

body {
    margin: 0;
}

#conference {
    position: relative;
    margin: 0;
    overflow: scroll;
    max-height: 100vh;
}

video {
    border-radius: 10px;
}

#local {
    position: absolute;
    width: 20%;
    min-width: 100px;
    max-width: 200px;
    bottom: 20px;
    right: 20px;
    z-index: 2;
    transform: rotateY(180deg);
    -webkit-transform:rotateY(180deg); /* Safari and Chrome */
    -moz-transform:rotateY(180deg); /* Firefox */
}

#remote {
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

#remote>video {
    flex: 1;
    max-height: 100vh;
}

Here should be the result:

What you can do next

Last updated