ApsaraVideo Real-time Communication (ARTC) SDK for Web is a set of web-based real-time communication development tools provided by Alibaba Cloud. The SDK allows you to integrate real-time interaction features, such as high-quality audio and video calling and real-time messaging, into a web client. This topic describes how to build your own ARTC application.
Step 1: Create an application
Log on to the ApsaraVideo Live console.
In the left-side navigation pane, choose
.Click Create Application.
Enter a custom name in the Instance Name field, select Terms of Service, and then click Buy Now.
After the application is created, refresh the Applications page to view the application.
NoteBy default, no fees are incurred when you create an application. You are charged based on your actual usage in the cloud. For more information, see Billing of ARTC.
Step 2: Obtain the application ID and AppKey
After you create an application, find the application in the application list and click Manage in the Actions column. On the Basic Information tab, obtain the values of Application ID and AppKey.
Step 3: Integrate and use the SDK
Integrate the SDK.
Use a script
Import the SDK script into your HTML page.
<script src="https://g.alicdn.com/apsara-media-box/imp-web-rtc/6.11.8/aliyun-rtc-sdk.js"></script>
Use npm
Use npm to install the SDK in your project.
npm install aliyun-rtc-sdk --save
Initialize the engine.
// Use one of the following methods. // Run the following command if you use npm to integrate the SDK. import AliRtcEngine from 'aliyun-rtc-sdk'; // Run the following command if you use a script to integrate the SDK. const AliRtcEngine = window.AliRtcEngine; // Check the environment. const checkResult = await AliRtcEngine.isSupported(); if (!checkResult.support) { // If the environment is unavailable, you are prompted to change or upgrade the browser. } // Create an AliRtcEngine instance, which can be saved as a global variable. const aliRtcEngine = AliRtcEngine.getInstance();
After you create an AliRtcEngine instance, you need to configure settings to listen to and handle relevant events.
// Handle the event that the local user leaves the channel. aliRtcEngine.on('bye', (code) => { // code indicates the reason for leaving the channel. For more information, see the API reference. console.log(`bye, code=${code}`); // Configure your handling logic, such as exiting the calling page. }); // Listen to the event that a remote user gets online. aliRtcEngine.on('remoteUserOnLineNotify', (userId, elapsed) => { console.log(`The user ${userId} has joined the channel. Time consumed: ${elapsed} seconds.`); // Configure your handling logic, such as displaying the module of the remote user. }); // Listen to the event that a remote user gets offline. aliRtcEngine.on('remoteUserOffLineNotify', (userId, reason) => { // reason indicates the reason why the remote user gets offline. For more information, see the API reference. console.log(`The user ${userId} has left the channel. Reason: ${reason}.`); // Configure your handling logic, such as destroying the module of the remote user. }); // Listen to the event that the state of subscription to a remote stream changes. aliRtcEngine.on('videoSubscribeStateChanged', (userId, oldState, newState, interval, channelId) => { // oldState and newState are parameters of AliRtcSubscribeState. The valid values of the parameters are 0 (initialized), 1 (unsubscribed), 2 (subscribing), and 3 (subscribed). // interval specifies the time elapsed for the change between two states, in milliseconds. console.log(`The state of subscription to the remote user ${userId} in the channel ${channelId} is changed from ${oldState} to ${newState}.`); // Configure the handling logic for the remote stream. // Call setRemoteViewConfig to play the remote stream if the value of newState changes to 3. // Stop the playback if the value of newState changes to 1. }); // Listen to the event that the authentication information expires. aliRtcEngine.on('authInfoExpired', () => { // The callback is triggered when the authentication information expires. // You must obtain data such as a token again and then call refreshAuthInfo to update the authentication information. aliRtcEngine.refreshAuthInfo({ userId, token, timestamp }); }); // Listen to the event that the authentication information is about to expire. aliRtcEngine.on('authInfoWillExpire', () => { // The callback is triggered 30 seconds before the authentication information expires. After you receive the callback, update the authentication information in a timely manner. // If you want to keep staying in the channel, you must obtain data such as a token again and then call joinChannel to join the channel again. });
Join a channel.
// Set the channel mode. Valid values: communication and interactive_live. aliRtcEngine.setChannelProfile('interactive_live'); // Specify the user role. This setting takes effect only in the interactive mode. // Valid values: interactive and live. The value interactive specifies the streamer role who can ingest and pull streams. The value live specifies the viewer role who can only pull streams. aliRtcEngine.setClientRole('interactive'); // Generate authentication information locally or from the server. For more information, see Token-based authentication. const appId = 'yourAppId'; // Obtain the application ID from the console. const appKey = 'yourAppKey'; // Obtain the AppKey from the console. Do not disclose your AppKey in the production environment. const channelId = 'AliRtcDemo'; // Specify the channel ID. The ID can contain only letters and digits. const userId = 'test1'; // Specify the user ID. The ID can contain only letters and digits. const userName = 'Test user 1'; // Specify the username. const timestamp = Math.floor(Date.now() / 1000) + 3600; // Specify the expiration timestamp. For example, a value of 3600 specifies that the token expires an hour after it is generated. try { const token = await generateToken(appId, appKey, channelId, userId, timestamp); // Join the channel. The token and nonce parameters are returned by the server. await aliRtcEngine.joinChannel({ channelId, userId, appId, token, timestamp, }, userName); // You succeed in joining the channel. Continue to perform subsequent operations. } catch (error) { // You fail to join the channel. }
Start preview and stream ingest. By default, local audio and video data is automatically collected and ingested to Global Realtime Transport Network (GRTN) after you join the channel. You can preview your local stream by performing the following operations.
Add the VIDEO element whose
id
islocalPreviewer
to the HTML code.<video id="localPreviewer" muted style="display: block;width: 320px;height: 180px;background-color: black;" ></video>
Call
setLocalViewConfig
and pass in the element ID to start preview.// For the first parameter, pass in HTMLVideoElement or specify the element ID. If you set the value to null, the preview is stopped. // Set the value of the second parameter to 1 or 2. The value 1 specifies that the camera stream is previewed. The value 2 specifies that the screen-sharing stream is previewed. aliRtcEngine.setLocalViewConfig('localPreviewer', 1);
Subscribe to remote audio and video streams. By default, you are automatically subscribed to the audio and video streams of other streamers after you join the channel. Audio streams are automatically played. To play camera streams or screen-sharing streams, call
setRemoteViewConfig
to configure the settings.Add the DIV element whose
id
isremoteVideoContainer
as a container to the HTML code.<div id="remoteVideoContainer"></div>
If the state of subscription to a remote video stream is changed to subscribed, call
setRemoteViewConfig
to play the stream. If the state of subscription to a remote video stream is changed to unsubscribed, remove the stream.// Save the Video element. const remoteVideoElMap = {}; // Set the remoteVideoContainer element. const remoteVideoContainer = document.querySelector('#remoteVideoContainer'); function removeRemoteVideo(userId) { const el = remoteVideoElMap[userId]; if (el) { aliRtcEngine.setRemoteViewConfig(null, userId, 1); el.pause(); remoteVideoContainer.removeChild(el); delete remoteVideoElMap[userId]; } } // The following sample code is the same as the description about videoSubscribeStateChanged in Step 2. aliRtcEngine.on('videoSubscribeStateChanged', (userId, oldState, newState, interval, channelId) => { // oldState and newState are parameters of AliRtcSubscribeState. The valid values of the parameters are 0 (initialized), 1 (unsubscribed), 2 (subscribing), and 3 (subscribed). // interval specifies the time elapsed for the change between two states, in milliseconds. console.log(`The state of subscription to the remote user ${userId} in the channel ${channelId} is changed from ${oldState} to ${newState}.`); // The following sample code provides a handling example. if (newState === 3) { const video = document.createElement('video'); video.autoplay = true; video.setAttribute('style', 'display: block;width: 320px;height: 180px;background-color: black;'); remoteVideoElMap[userId] = video; remoteVideoContainer.appendChild(video); // For the first parameter, pass in HTMLVideoElement. // For the second parameter, specify the ID of the remote user. // Set the value of the third parameter to 1 or 2. The value 1 specifies that the camera stream is previewed. The value 2 specifies that the screen-sharing stream is previewed. aliRtcEngine.setRemoteViewConfig(video, userId, 1); } else if (newState === 1) { removeRemoteVideo(userId); } });
End the process.
// Stop the local preview. await aliRtcEngine.stopPreview(); // Leave the channel. await aliRtcEngine.leaveChannel(); // Destroy the instance. aliRtcEngine.destroy();
Demo
Prerequisites
To try the demo, you need to start an HTTP service in your development environment. If you do not have the npm package that is used to install http-server
, run the npm install --global http-server
command to install the server globally.
Step 1: Create a directory
Create a folder named demo, and create the quick.html
and quick.js
files in the folder based on the following directory structure.
- demo
- quick.html
- quick.js
Step 2: Edit the quick.html file
Copy the following code to the quick.html file and save the file.
Step 3: Edit the quick.js file
Copy the following code to the quick.js file, specify the appId and appKey parameters in the code, and save the file.
Step 4: Run the demo
In the terminal, open the demo folder and run
http-server -p 8080
to start an HTTP service.Create a tab in the browser. On the tab, access
localhost:8080/quick.html
, fill in your channel ID and user ID, and click the Join Channel button.Create another tab in the browser. On the tab, access
localhost:8080/quick.html
, fill in the same channel ID and another user ID, and click the Join Channel button.Verify that you are automatically subscribed to the media stream of the remote user.