How to Build a WebRTC Video Chat App in 24 Hrs
WebRTC Video Chat in 24 hrs
WebRTC (Web Real-time Communication) is a set of open-source standards + JavaScript APIs that enables the transfer of video data, audio data, and media from the browser of one client to the browser of another client in real-time, without installing plugins, extensions or frameworks.
However, WebRTC comes with a few challenges:
- Setting up Signaling servers is a bit tricky
WebRTC cannot handle the exchange of session descriptions (SDP) and ICE candidates between the peers efficiently.
- Handling connection is hard
For a stable connection, the system must manage NAT traversal, STUN/ TURN server and reconnection logic. WebRTC cannot do it all.
- Managing media tracks can get messy
In scenarios with multiple streams, WebRTCs can neither switch the cameras or mics nor add/remove the participants dynamically.
Solution: MirrorFly’s video chat SDK
MirrorFly takes care of the video data transfer, media streaming and connection management efficiently and securely with a robust real-time communication infrastructure.
In this tutorial, we’ll explain the steps to develop a secure video chat based on the WebRTC standard for establishing a connection and exchanging information between clients using JavaScript.
The project will use MirrorFly video chat SDK to achieve low-code development within 10 mins. We’ll simply integrate MirrorFly call SDK for the web to add real-time calling features to your client app.
If you do not have an app already, check out this sample app to get started.
Right now, let’s get to the project.
Step 1: Setting up your Environment
Before integrating the SDK, you need to check if your browser supports it and obtain the license key.
Check Supported Browsers: The MirrorFly Call SDK supports the following browser versions:
- Edge: 13 or higher
- Chrome: 16 or higher
- Firefox: 11 or higher
- Safari: 7 or higher
Get the SDK License Key: You’ll need a license key to authenticate the SDK in your app.
If you do not have a license key yet:
- Step 1: Contact MirrorFly Team and get a MirrorFly User account.
- Step 2: Login to your Account.
- Step 3: Go to the ‘Application Info’ section in your dashboard and get the License Key.
Step 2: Integrate the Video Call SDK into Your JavaScript App
You can integrate the MirrorFly Video Call SDK using either the NPM package or by downloading the SDK files.
Option A: Integrate using NPM package
- Install MirrorFly SDK: Use the following command to install the mirrorfly-sdk npm package.
npm i mirrorfly-sdk
- Import the SDK: Import the SDK into the application file where you plan to use it.
import * as SDK from "mirrorfly-sdk";
Note: If you install using NPM, skip Option B.
Option B: Integrate using Downloaded Files
- Download and Extract: Download the JavaScript SDK files, extract them from the zip file, and copy them into your application.
- Include the Script: Include the script file into your
index.htmlfile.
<script src="./index.js"></script>
- SDK Object Availability: Once included, the SDK object will be available in your application to proceed with initialization.
Step 3: Initialize the Call SDK
To initialize your SDK, you’ll need to pass the license key. You’ll also need a set of call listeners to handle connection and call-related events:
- Define Callback Listeners: Define the necessary callback listeners to respond to connection status and call events, such as
incomingCallListenerandcallStatusListener.
const incomingCallListener = (res) => {};
const callStatusListener = (res) => {};
const userTrackListener = (res) => {};
const muteStatusListener = (res) => {};
const missedCallListener = (res) => {};
const callSwitchListener = (res) => {};
const inviteUsersListener = (res) => {};
const mediaErrorListener = (res) => {};
const callSpeakingListener = (res) => {};
const callUsersUpdateListener = (res) => {};
const callUserJoinedListener = (res) => {};
const callUserLeftListener = (res) => {};
const callConnectionQualityListener = (res) => {};
const helper = {}
const initializeObj = {
licenseKey: "XXXXXXXXXXXXXXXX",
callbackListeners: {
connectionListener,
incomingCallListener,
callStatusListener,
userTrackListener,
muteStatusListener,
missedCallListener,
callSwitchListener,
inviteUsersListener,
mediaErrorListener,
callSpeakingListener,
callUsersUpdateListener,
callUserJoinedListener,
callUserLeftListener,
callConnectionQualityListener,
helper
},
};
await SDK.initializeSDK(initializeObj);
- Initialize the SDK: Use the
initializeSDKmethod, pasting your license key into thelicenseKeyparameter.
Note: When in trial mode, sandbox servers are used by default; after purchase, this is upgraded to a dedicated server. The
initializeSDKmethod requires thelicenseKey(String, required) and thecallbackListeners(Object, required).
Step 4: Create and Connect a User
To make or receive calls, you must first register a user and connect to the MirrorFly server:
- Register a New User: Use the
SDK.registermethod with a unique user identifier (USER_IDENTIFIER).
await SDK.register('USER_IDENTIFIER');
The USER_IDENTIFIER can only contain lowercase alphanumeric characters, hyphens (-), and underscores (_).
- Connect to MirrorFly Server: Once registered, you will be provided with a username and password in the response data. Use these credentials to connect to the server.
A successful connection will return a statusCode of 200, and you can trace the connection status via the connectionListener callback function.
await SDK.connect('USERNAME', 'PASSWORD');
- Prepare User JID: The
userJidis the unique ID that allows you to connect with other users. You can generate a JID for any user using thegetJidmethod.
const userJid = SDK.getJid(USER_NAME)
Here the USER_NAME is the unique username obtained from the Register response.
Step 5: Making a Voice Call
Initiate a call using the makeVoiceCall method, providing the callee’s user JID.
- Initiate the Call: Pass the target user's JID in an array to the method. For one-to-one calls, set the
GROUP_IDparameter (the second argument) tonull.
SDK.makeVoiceCall(['USER_JID'], null, metadata,
(success, error) => {
if (error) {
// Error occured while making the call
}
if (success) {
// Call has been made successfully
}
});
If a one-to-one call feature is unavailable for your plan, a 403 exception will be thrown.
- Receive Tracks: The
callStatusListenercallback is triggered when the call is successfully initiated. To receive audio/video data (the user tracks), theuserTrackListenercallback must be registered in the caller's client app. You will receive your own track and the callee's track in this same callback method.
Step 6: Receiving, Answering, and Ending Calls
The client app needs to register callback listeners to handle incoming calls and manage the session.
- Receive an Incoming Call: The
incomingCallListenercallback must be registered in the callee’s client app. When a user calls, the callee receives the calling data (includingcallType,roomId, anduserJidof the initiator) in this callback.
// Callback Response Argument Structure
{
allUsers: ["USER1_JID", "USER2_JID", ...],
callTime: 1681905421215,
callType: "audio|video",
groupId: null|GROUP_ID,
localUser: BOOLEAN,
roomId: "wmupbhea0",
roomLink: "ndy-bmkb-eui",
status: "calling",
toUsers: ["USER_JID"],
userDetails: {},
userJid: "FROM_USER_JID",
usersStatus: [{}]
}
- Answer the Call: Use the
answerCallmethod to accept the incoming call:
SDK.answerCall((success, error) => {
if (error) {
// Error occured while answering the call
}
if (success) {
// Call has been answered successfully
}
});
When the call is answered, you will receive your own track and the caller's track via the registered userTrackListener.
- Play Audio/Video Tracks: You must supply the track object received in the callback method to an HTML audio/video element based on the track type.
Warning: For Audio/Video calls, you should not play your own Audio track.
- End the Call: Use the
endCallmethod to terminate the session.
SDK.endCall((success, error) => {
if (error) {
// Error occured while ending the call
}
if (success) {
// Call has been ended successfully
}
});
Want to learn more?
Appreciate you are upskilling on this topic. I hope you enjoyed this tutorial, as much as I enjoyed creating it. WebRTC is a truly powerful resource for video communication. When combined with a solution like MirrorFly, its potential multiplies, yielding modern video chat apps.
Check out some of my other WebRTC resources:
Stay tuned. I’m writing another interesting piece on WebRTC. I will post it shortly.