Live Streaming
  • iOS
  • Android
  • Web
  • Flutter
  • React Native : JavaScript
  • Electron
  • Unity3D
  • Windows
  • macOS
  • Linux
  • Overview
  • Live Streaming vs. Interactive Live Streaming
  • Develop your app
    • Live Streaming
      • Quick start
      • Enhance basic livestream
      • CDN
    • Interactive Live Streaming
  • Upgrade the livestream
    • Advanced features
      • Message signaling
        • Broadcast real-time messages to a room
        • Quotas and limits
      • Play media files
        • Play media files
      • Mix the live streams
  • Resources & Reference
    • SDK
    • Sample code
    • API reference
      • Client APIs
      • Server APIs
    • FAQs
    • Key concepts
  • Documentation
  • Live Streaming
  • Develop your app
  • Live Streaming
  • Quick start

Quick Start

Last updated:2023-06-07 16:17

Introdution

This guide describes how to integrate the SDK and implement a basic live streaming using ZEGOCLOUD's ZegoExpressEngine SDK.

Prerequisites

Before you begin, make sure you complete the following:

  • React Native 0.60.0 or later
  • An iOS device or iOS Simulator that is running on iOS 9.0 or later and supports audio and video. We recommend you use a real device.
  • An Android device or simulator that is running on Android 4.4 or later and supports audio and video. We recommend you use a real device (remember to enable USB debugging for the device).
  • Sign up and create a project in Admin Console.
  • Activate the Live Streaming service.

Integrate the SDK

Optional: Create a new project

Skip to this step if a project already exists.

Create a new project

After configuring the development environment, run the command react-native init YourProject.

Import the SDK

  1. Enter the root directory of your project, open the package.json, and add the "zego-express-engine-reactnative": "^x.y.z" to the dependencies.

x.y.z is the latest SDK version number, which can be obtained by running an npm command.

  1. In the root directory of your project, run the npm install zego-express-engine-reactnative --save command or the yarn add zego-express-engine-reactnative command to install the SDK.

  2. Go to the iOS root directory, run the pod install command to install the dependencies.

Once you've done the operations above, you will be available to use the zego-express-engine-reactnative SDK in your project either in JavaScript or TypeScript (TypeScript is recommended).

Add permissions

Permissions can be set as needed.

  • Android

Open the app/src/main/AndroidManifest.xml file, and add the following code:

<!-- Permissions required by the SDK -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Permissions required by the App -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

Because Android 6.0 requires dynamic permissions for some important permissions, you will need to apply for dynamic permissions by referring to the following code after applying for static permissions through the AndroidMainfest.xml file.

import {PermissionsAndroid} from 'react-native';

const granted = PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.CAMERA,
                                        PermissionsAndroid.RECORD_AUDIO);
granted.then((data)=>{

        if(!data) {
            const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, PermissionsAndroid.PERMISSIONS.CAMERA];
            PermissionsAndroid.requestMultiple(permissions);
        }
    }).catch((err)=>{
    console.log(err.toString());
    })
}
  • iOS
  1. In Xcode, select the target project, go to Info > Custom iOS Target Properties.

AddiOS Privacy

  1. Add the + button to add microphone and camera permissions.

    • Privacy - Camera Usage Description
    • Privacy - Microphone Usage Description

After the permission is added, it will be shown as below:

AddiOS Privacy Done

Implement a basic live streaming

Understand the tech

The following diagram shows the basic process of User A playing a stream published by User B:

/Pics/in_app_chat/17395_2.png

For a better understanding, you can check the key concepts of ZegoExpressEngine SDK:

Sample code

Here is the sample code for implementing ve streaming functions. Feel free to refer to it when developing.

Create a ZegoExpressEngine engine

Call the createEngineWithProfile method and set the appID and appSign parameters to the applied AppID and AppSign, respectively.

To register callbacks, you can implement some methods in ZegoEventListener as required and call the on method after engine creation to set callbacks.

The SDK also supports Token-based authentication. If you want to upgrade the authentication mode, see Guide for upgrading the authentication mode from using the AppSign to Token.

// Import
import ZegoExpressEngine from 'zego-express-engine-reactnative';

// Use the general scenario.
const profile = {
appID : xxx,
// The AppSign can only meet simple authentication requirements. If you want to use the Token for authentication, which is securer, see [Guide for upgrading the authentication mode from using the AppSign to Token](https://docs.zegocloud.com/faq/token_upgrade).
// You can obtain the AppSign in the [ZEGOCLOUD Admin Console](https://console.zego.im/dashboard). The format is similar to @"39011cbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".
appSign: '39011cbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
scenario : 0
};

ZegoExpressEngine.createEngineWithProfile(profile)

Log in to a room

Log in

Call the loginRoom method to log in to a room. If the room does not exist, calling this method will create and log in to the room.

The values of the roomID and user parameters are generated locally, but the following conditions must be met:

  • The value of roomID must be globally unique under the same AppID.
  • The value of userID must be globally unique under the same AppID. You are advised to associate userID with the account system of your service.
let roomConfig = new ZegoRoomConfig();
// If you use the AppSign for authentication, you do not need to set the `token` parameter. If you want to use the Token for authentication, which is securer, see [Guide for upgrading the authentication mode from using the AppSign to Token](https://docs.zegocloud.com/faq/token_upgrade).
// roomConfig.token = "xxxx";
// The `onRoomUserUpdate` callback can be received only when `ZegoRoomConfig` in which the `isUserStatusNotify` parameter is set to `true` is passed.
roomConfig.isUserStatusNotify = true;
// Room login.
// Log in to a room.
ZegoExpressEngine.instance().loginRoom('room1', {'userID': 'id1', 'userName': 'user1'}, roomConfig);

Listen for callback events after room login

Based on your service requirements, listen for event notifications after room login, such as room connection, user, and stream status updates.

  • roomStateUpdate: room connection status callback. After a user logs in to a room, when the room connection status changes (for example, the room is disconnected or login authentication fails), the SDK triggers this callback to send a notification.

  • roomUserUpdate: user status update callback. After a user logs in to a room, when another user joins or leaves the room, the SDK triggers this callback to send a notification.

    The roomUserUpdate callback can be received only when ZegoRoomConfig in which the isUserStatusNotify parameter is set to true is passed in the loginRoom method.

  • roomStreamUpdate: stream status update callback. After a user logs in to a room, when another user in the room publishes or deletes an audio or video stream, the SDK triggers this callback to send a notification.

  • The roomUserUpdate callback can be received only when ZegoRoomConfig in which the isUserStatusNotify parameter is set to true is passed in the loginRoom method.
  • Generally, if a user wants to play a video published by another user, the user can call the startPlayingStream method in the stream status update (stream addition) callback to play the audio and video streams.
// Common room-related callbacks

ZegoExpressEngine.instance().on('roomStateUpdate', (roomID, state, errorCode, extendedData) => {
  // Room connection status callback. After a user logs in to a room, when the room connection status changes (for example, the room is disconnected or login authentication fails), the SDK triggers this callback to send a notification.
}); ;


ZegoExpressEngine.instance().on('roomUserUpdate', (roomID, updateType, userList) => {
  // User status update callback. After a user logs in to a room, when another user joins or leaves the room, the SDK triggers this callback to send a notification.
});

ZegoExpressEngine.instance().on('roomStreamUpdate', (roomID, updateType, streamList) => {
  // Stream status update callback. After a user logs in to a room, when another user in the room publishes or deletes an audio or video stream, the SDK triggers this callback to send a notification.
});

Publish streams

Start to publish streams

Call the startPublishingStream method and set the streamID parameter to publish a local audio and video stream to remote users.

The value of streamID must be globally unique under the same AppID. If different streams are published with the same streamID, the ones that are published after the first one will fail.

/** Start to publish streams.*/
ZegoExpressEngine.instance().startPublishingStream("streamID");

Optional: Start the local preview

Set the preview view and start the local preview

To view the local videos, call the startPreview method to set the preview view and start the local preview.

import { findNodeHandle } from 'react-native';

// Obtain `ref` of `zego_play_view`.
let localViewRef = findNodeHandle(this.refs.zego_preview_view);

// Start the local preview.
ZegoExpressEngine.instance().startPreview({
    'reactTag': localViewRef,
    'viewMode': 0,
    'backgroundColor': 0
});

// react render
render() {
    return (
        <View>
            <ZegoTextureView ref='zego_preview_view'/>
        </view>
    )
}

Listen for callback events after stream publishing starts

Based on your service requirements, listen for event notifications after stream publishing starts, such as stream publishing status updates.

publisherStateUpdate: stream publishing status update callback. If the stream publishing status changes (for example, a stream publishing exception occurs due to network interruption) after the stream publishing method is successfully called, the SDK triggers this callback to send a notification while retrying to publish the stream.

    ZegoExpressEngine.instance().on("publisherStateUpdate", (streamID, state, errorCode, extendedData) => {
    // If the stream publishing status changes (for example, a stream publishing exception occurs due to network interruption) after the stream publishing method is successfully called, the SDK triggers this callback to send a notification while retrying to publish the stream
    //....
});

Play streams

1. Start to play streams

Call the startPlayingStream method and set the streamID parameter to play an audio and video stream published by a remote user.

  • You can obtain the value of streamID corresponding to the stream that has been published by a remote user from the roomStreamUpdate callback.
  • The value of streamID must be globally unique.
import { findNodeHandle } from 'react-native';

// Obtain `ref` of `zego_play_view`.
let remoteViewRef = findNodeHandle(this.refs.zego_play_view);

// Start to play streams.
ZegoExpressEngine.instance().startPlayingStream("streamID", {
    'reactTag': remoteViewRef,
    'viewMode': 0,
    'backgroundColor': 0
});

// react render
render() {
    return (
        <View>
            <ZegoTextureView ref='zego_play_view'/>
        </view>
    )
}

Listen for callback events after stream playing starts

Based on your service requirements, listen for event notifications after stream playing starts, such as stream playing status updates.

playerStateUpdate: stream playing status update callback. If the stream playing status changes (for example, a stream playing exception occurs due to network interruption) after the stream playing method is successfully called, the SDK triggers this callback to send a notification while retrying to play the stream.

ZegoExpressEngine.instance().on("playerStateUpdate", (streamID, state, errorCode, extendedData) => {
    /** If the stream playing status changes (for example, a stream playing exception occurs due to network interruption) after the stream playing method is successfully called, the SDK triggers this callback to send a notification while retrying to play the stream.*/
    //....
});

Test out real-time audio and video features

We recommend you run your project on a real device. If your app runs successfully, you should hear the sound and see the video captured locally from your device.

To test out the real-time audio and video features, visit the ZEGO Express Web Demo, and enter the same AppID, Server and RoomID to join the same room. If it runs successfully, you should be able to view the video from both the local side and the remote side, and hear the sound from both sides as well.

In audio-only scenarios, no video will be captured and displayed.

Stop publishing or playing streams

Stop the stream publishing and preview

Call the stopPublishingStream method to stop publishing local audio or video streams and end the call.

/** Stop publishing streams. */
ZegoExpressEngine.instance().stopPublishingStream();

If the local preview is started, call the stopPreview method to stop it based on your service requirements after stopping publishing streams.

// Stop the local preview.
ZegoExpressEngine.instance().stopPreview();

Stop playing streams

Call the stopPlayingStream method to stop playing audio and video streams published by remote users.

// Stop playing streams.
ZegoExpressEngine.instance().stopPlayingStream("streamID");

Log out of a room

Call the logoutRoom method to log out of a room. In this case, you will receive the roomStateUpdate callback locally, which carries the result of calling the logoutRoom method, and stream publishing, stream playing, and the local preview will all be stopped.

// Log out of a room.
ZegoExpressEngine.instance().logoutRoom('room1');

Destroy a ZegoExpressEngine instance

Call the destroyEngine method to destroy a ZegoExpressEngine instance so that the resources used by the SDK can be released.

ZegoExpressEngine.destroyEngine();

When destroying a ZegoExpressEngine instance, you can use the await keyword as required to wait asynchronously, ensuring that the hardware resources are completely released.

FAQ

1. Can I integrate the SDK with React Native 0.60.0 or earlier?

The answer is No. The zego-express-engine-reactnative SDK only supports React Native 0.60.0 or later. To integrate the SDK, upgrade the project version first.

2. After importing the SDK into the project, do I need to manually run the 'react-native link zego-express-engine-reactnative' command to link Native Modules?

The answer is No. React Native has supported automatic linking to Native Modules starting from version 0.60.0.

Page Directory