ZEGO Live
  • iOS
  • Android : Java
  • Introduction
  • Sample app
  • Getting started
  • Guides
    • Room
    • Co-host
    • Face beautify
    • Sound effects
    • Room related Server APIs
  • Error codes

Build a live video streaming

Last updated:2022-05-26 10:02

ZEGO Live provides you the capability to build an interactive live streaming application by encapsulating the Express-Video SDK and ZIM SDK. This document describes how to build a live video streaming with the ZEGO Live SDK.




Prerequisites

Understand the process

The following diagram shows the basic process of creating a live room and a participant (user B) playing a stream published by the host (user A).

/Pics/ZEGOLive/quickstart.png

Integrate the ZEGOLive SDK

The Server APIs that we used to implement live room related business logic in the ZEGO Live sample app is only for experience and debugging purposes.

To build your own live streaming app, you can refer to ours to design your own business server APIs and replace them in our sample code. For more details about those Server APIs, see Room related Server APIs.

To integrate the SDK, do the following:

  1. Download the Sample codes, copy the zegolive module to your project (create a new project if you don't have an existing project).

  2. Add the following code to the settings.gradle file:

    include ':zegolive'
  3. Modify the build.gradle file of your application, add the following code to the dependencies node:

    implementation project(':zegolive')

    /Pics/ZEGOLive/lib_app_config.png

  4. Modify the build.gradle file of your project, add the following code to the repositories node:

    If your Android Studio version is higher than "bumblebee 2021.1.1 patch 1", please modify the maven configuration in the setting.gradle. For more details, see How to add the Maven repositories in Android Studio version bumblebee?

    maven { url 'https://www.jitpack.io' }

    /Pics/ZIMChatRoom/en/jitpack.png

  5. Click sync now.

Add permissions

Permissions can be set as needed.

Open the file app/src/main/AndroidManifest.xml, 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" />

    <!-- Permissons 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" />

Note: For Android 6.0 or later, some important permissions must be requested at runtime rather than declared statically in the file AndroidMainfest.xml, therefore, you need to add the following code to do so (requestPermissions is a method of an Android Activity).

String[] permissionNeeded = {
        "android.permission.CAMERA",
        "android.permission.RECORD_AUDIO"};

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this, "android.permission.CAMERA") != PackageManager.PERMISSION_GRANTED ||
        ContextCompat.checkSelfPermission(this, "android.permission.RECORD_AUDIO") != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(permissionNeeded, 101);
    }
}

Prevent class name obfuscation

To prevent the ZEGO SDK public class names from being obfuscated, you can add the following code in the file proguard-rules.pro.

-keep class **.zego.**{*;}

Initialize the ZEGOLive SDK

To initialize the ZEGOLive SDK, get the RoomManager instance, pass the AppID of your project.

// The AppID you get from ZEGOCLOUD Admin Console. 
long appID = 214124124L;
// Initialize the SDK. We recommend you call this method when the application starts.
// The last parameter refers to the Application object of the ZEGOlive SDK.
ZegoRoomManager.getInstance().init(appID, this);

To receive event callbacks, call the setListener to listen for and handle various events as needed.

ZegoMessageService messageService = ZegoRoomManager.getInstance().messageService;
messageService.setListener(new ZegoMessageServiceListener() {
    // Implement the callback handling logic as needed.
});

ZegoUserService userService = ZegoRoomManager.getInstance().userService;
userService.setListener(new ZegoUserServiceListener() {
    // Implement the callback handling logic as needed.        
});

ZegoRoomService roomService = ZegoRoomManager.getInstance().roomService;
roomService.setListener(new ZegoRoomServiceListener() {
    // Implement the callback handling logic as needed. 
});

Log in

To access the ZEGOLive service, you must log in first.

  • For business security, you will need to provide a token for the ZIM SDK to validate the login privilege. For details, see Authentication.
  • For debugging, you can refer to our Sample code to generate tokens on your app client.
ZegoUserInfo user  = new ZegoUserInfo();
// Set the user related properties. 
user.setUserID("USER_ID");
user.setUserName("USER_NAME");

// Your token. 
String token = "xxx";  
ZegoRoomManager.getInstance().userService.login(user, token, new ZegoRoomCallback() {
    @Override
    public void onRoomCallback(int errorCode) {
        // Callback for the login result. 
    }
});

Start the local video preview

Before creating a live room to start live streaming, you can call the playVideoStream method to start the local video preview.

// The [userID] can be used to specify which user's view you want to view. 
// To preview your own local video view, pass in your userID.
// streamView view is a view for the local video preview.
ZegoRoomManager.getInstance().deviceService.playVideoStream(userID, streamView);

Create/Join a live room

  • You become a Host after creating a room, and you can take a seat and start live streaming upon creating.
  • You become a Participant after joining a live room, and you can watch the live streaming and be a co-host to interact.
  • To prevent listeners in a room from being able to speak directly without taking a speaker seat, you will need to provide a token for the RTC SDK to validate whether you have the privileges to create or join a room. For details, see Use Tokens for authentication.
  • This Token can be the same as the Token you provided for login.

To create a live room, call the createRoom method:

String roomID = "YOUR_ROOM_ID";
String roomName = "YOUR_ROOM_NAME";
ZegoRoomManager.getInstance().roomService.createRoom(roomID, roomName, token, new ZegoRoomCallback() {
   @Override
   public void onRoomCallback(int errorCode) {
   // Callback for the result of create a live room. 
   }
});

After a live room is created, to start live streaming, the host will need to call the takeSeat method to speak. And the SDK automatically publishes the streams when the host takes a seat successfully.

ZegoRoomManager.getInstance().userService.takeSeat(new ZegoRoomCallback(){
   @Override
   public void onRoomCallback(int errorCode) {
   // Callback for the returned result of take a seat.
   }
});

To join a live room, call the joinRoom method.

String roomID = "ROOM_ID";
ZegoRoomManager.getInstance().roomService.joinRoom(roomID, token, new ZegoRoomCallback() {
   @Override
   public void onRoomCallback(int errorCode) {
   // Callback for the result of join a live room. 
   }
});

After joining a live room, for a participant to watch the live streaming, he will need to call the playVideoStream method to play the host's published streams.

// The [userID] can be used to specify which user's view you want to view. 
// You can get the userID of the host in room info.
// streamView view is a view for the local video preview.
ZegoRoomManager.getInstance().deviceService.playVideoStream(userID, streamView);

Send/Receive text messages

To send text messages in the room, call the sendTextMessage method.

ZegoRoomManager.getInstance().messageService.sendTextMessage("YOUR_MESSAGE", new ZegoRoomCallback() {
   @Override
   public void onRoomCallback(int errorCode) {
   // Callback for the result of send a message.
   }
});

To receive the text messages, listen for the callback onReceiveTextMessage.

ZegoRoomManager.getInstance().messageService.setListener(new ZegoMessageServiceListener() {
    @Override
    public void onReceiveTextMessage(ZegoTextMessage textMessage) {
        // Receives and handle the messages (messages and sender ID).   
    }
});

Renew a Token

30 seconds before a Token expires, the SDK sends out a notification through the onRoomTokenWillExpire callback.

Upon receiving this callback, you need to get a new Token from your app server first, and then pass the new token to the renewToken method.

@Override
public void onRoomTokenWillExpire(int remainTimeInSecond, String roomID) {
    ZegoUserInfo selfUser = ZegoRoomManager.getInstance().userService.localUserInfo;
    ZegoTokenManager.getInstance().getToken(selfUser.getUserID(), true, new ZegoTokenCallback() {
        @Override
        public void onTokenCallback(int errorCode, @Nullable String token) {
            if (errorCode == ZegoRoomErrorCode.SUCCESS) {
                ZegoRoomManager.getInstance().roomService.renewToken(token, roomID);
            }
        }
    });
}

Leave a live room

Before the host leaves the live room, he will need to call the leaveSeat to leave the seat first. And the SDK automatically stops publishing streams when the host leaves the seat successfully.

ZegoRoomManager.getInstance().userService.leaveSeat(new ZegoRoomCallback(){
   @Override
   public void onRoomCallback(int errorCode){
   // Callback for the result of leave a seat.
   }
});

To leave the live room, call the leaveRoom method. And the SDK stops all the stream publishing and playing operations simultaneously.

ZegoRoomManager.getInstance().roomService.leaveRoom(new ZegoRoomCallback() {
   @Override
   public void onRoomCallback(int errorCode) {
   // Callback for the result of leave a live room. 
   }
});

Log out

To finish the ZEGOLive service, call the logout method.

ZegoRoomManager.getInstance().userService.logout();

Deinitialize the ZEGOLive SDK

To deinitialize the SDK to make it uninitialized, call the uninit method.

ZegoRoomManager.getInstance().unInit();

FAQ

Question: The error Lambda expressions are not supported at language level '7' occurs after importing the zegolive module.

Answer: Lambda expressions are only supported in Java 8 or later. You will need to add the following code into the build.gradle file of your project first:

android {
    ...
    // Configure only for each module that uses Java 8
    // language features (either in its source code or
    // through dependencies).
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}