Live Audio Room
  • iOS
  • Android : Java
  • Introduction
  • Sample app
  • Getting started
  • Guides
    • Manage rooms
    • Manage audio
    • Manage speaker seats
    • Manage messages
  • Error codes
  • Documentation
  • Live Audio Room
  • Getting started

Build a live audio room

Last updated:2022-04-29 15:24

This document describes how to use the zegoliveaudioroom SDK to build a live audio room.


Prerequisites

Understand the process

The following diagram shows the basic process of creating a live audio room and taking speaker seats to speak:

/Pics/ZIMChatRoom/ZIMChatRoom_process_EN.png

Integrate the zegoliveaudioroom SDK

To integrate the SDK, do the following:

  1. Download the Sample codes, copy the zegoliveaudioroom module to your project (if you have no project, create a new one).

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

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

    implementation project(':zegoliveaudioroom')

    /Pics/ZIMChatRoom/en/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 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.BLUETOOTH" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

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.RECORD_AUDIO"};

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (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 zegoliveaudioroom SDK

To initialize the zegoliveaudioroom SDK, get the ZegoRoomManager instance, pass the AppID and AppSign of your project.

long appID = 214124124L;  // The AppID you get from ZEGO Admin Console. 

// Initialize the SDK. We recommend you call this method when the application starts.
// The last parameter refers to the Application object of the app.
ZegoRoomManager.getInstance().init(appID, this);

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

ZegoGiftService giftService = ZegoRoomManager.getInstance().giftService;
giftService.setListener(new ZegoGiftServiceListener() -> {
            // Implement the callback handling logic 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.        
});
ZegoSpeakerSeatService seatService = ZegoRoomManager.getInstance().speakerSeatService;
seatService.setListener(new ZegoSpeakerSeatServiceListener(){
           // 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 signaling service of Live Audio Room with the zegoliveaudioroom SDK, 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");
String token = "xxx";  // The token you get from your app server. 


/**
 * User to log in.
 * @param userInfo refers to the user information. You only need to enter the user ID and username.
 * @param token    refers to the authentication token. 
 * @param callback refers to the callback for log in.
 */
ZegoRoomManager.getInstance().userService.login(user, token, new ZegoRoomCallback() {
    @Override
    public void roomCallback(int errorCode) {
        // Callback for the login result. 
    }
});

Create/Join a live audio room

  • You become a Host after creating a live audio room, and you owe more permissions, such as closing untaken speaker seats, removing a specified listener from the speaker seat, etc.
  • You become a Listener after joining a live audio room, you can take a speaker seat to be a speaker or leave the speaker seat to become a listener again.
  • 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 audio room, call the createRoom method:

String roomID = "YOUR_ROOM_ID";
String roomName = "YOUR_ROOM_NAME";

/**
 * Create a room.
 * @param roomID   roomID refers to the room ID, the unique identifier of the room. This is required to join a room and cannot be null.
 * @param roomName roomName refers to the room name. This is used for display in the room and cannot be null.
 * @param token    token refers to the authentication token. 
 * @param callback callback refers to the callback for create a room.
 */
ZegoRoomManager.getInstance().roomService.createRoom(roomID, roomName, token, new ZegoRoomCallback() {
    @Override
    public void roomCallback(int errorCode) {
        // Callback for the result of create a live audio room. 
    }
});

To join a live audio room, call the joinRoom method:

String roomID = "ROOM_ID";

/**
 * Join a room.
 * @param roomID   refers to the ID of the room you want to join, and cannot be null.
 * @param token    token refers to the authentication token.
 * @param callback callback refers to the callback for join a room.
 */
ZegoRoomManager.getInstance().roomService.joinRoom(roomID,token,new ZegoRoomCallback() {
    @Override
    public void roomCallback(int errorCode) {
        // Callback for the result of join a live audio room. 
    }
});

Send/Receive messages in the room

In a live audio room, both Host and Listeners can send and receive messages.

To send messages, call the sendTextMessage method with message content.

/**
 * Send IM text message.
 * <p>Description: This method can be used to send IM text message, and all users in the room will receive the
 * message notification.</>
 * <p>Call this method at:  After joining the room</>
 *
 * @param text     refers to the text message content, which is limited to 1kb.
 * @param callback refers to the callback for send text messages.
 */
ZegoRoomManager.getInstance().messageService.sendTextMessage("YOUR_MESSAGE", new ZegoRoomCallback() {
   @Override
   public void roomCallback(int errorCode) {
   // Callback for the result of send a message. 
   }
});

To receive messages, listen for the ZegoMessageServiceListener callback.

ZegoMessageService messageService = ZegoRoomManager.getInstance().messageService;
messageService.setListener(new ZegoMessageServiceListener() -> {
            // This callback will be triggered when new messages are received. 
});

Take a speaker seat

To take a speaker seat to speak, call the takeSeat method. And the SDK publishes streams simultaneously.

// Takes a speaker seat. 
int seatIndex = 2;  // The ID of the seat be taken. 
/**
 * Take the speaker seat.
 * <p>Description: This method can be used to help a listener to take a speaker seat to speak. And at the same
 * time,the microphone will be enabled, the audio streams will be published.</>
 * <p>Call this method at:  After joining the room</>
 *
 * @param seatIndex seatIndex to take
 * @param callback  operation result callback
 */
ZegoRoomManager.getInstance().speakerSeatService.takeSeat(seatIndex,new ZegoRoomCallback(){
   @Override
   public void roomCallback(int errorCode){
   // Callback for the result of take a speaker seat. 
   }
});

When there is a new listener takes a seat and becomes a speaker, all participants in the room receive notifications through the ZegoSpeakerSeatServiceListener callback. You can set up a UI refresh action for this callback as needed.

ZegoSpeakerSeatService seatService = ZegoRoomManager.getInstance().speakerSeatService;
seatService.setListener(new ZegoSpeakerSeatServiceListener(){
            // This callback will be triggered when the status of speaker seats changes. 
})

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 speaker seat

To leave a speaker seat and become a listener again, call the removeUserFromSeat method. And the SDK stops publishing streams simultaneously.

// Leaves a speaker seat. 
int seatIndex = 2;  // The ID of the seat.

/**
 * Remove a user from speaker seat.
 * <p>Description: This method can be used to remove a specified user (except the host) from the speaker seat. </>
 *
 * @param seatIndex refers to the seat index of the user you want to remove.
 * @param callback  refers to the callback for remove a user from the speaker seat.
 */
ZegoRoomManager.getInstance().speakerSeatService.removeUserFromSeat(seatIndex,new ZegoRoomCallback(){
   @Override
   public void roomCallback(int errorCode){
   // Callback for the result of leave a speaker seat. 
   }
});

When there is an existing speaker leaves a seat and becomes a listener again, all participants in the room receive notifications through the ZegoSpeakerSeatServiceListener callback. You can set up a UI refresh action for this callback as needed.

ZegoSpeakerSeatService seatService = ZegoRoomManager.getInstance().speakerSeatService;
seatService.setListener(new ZegoSpeakerSeatServiceListener(){
            // This callback will be triggered when the status of speaker seats changes. 
})

Leave a live audio room

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

/**
 * Leave the room.
 * <p>Description: This method can be used to leave the room you joined. The room will be ended when the Host
 * leaves, and all users in the room will be forced to leave the room.</>
 * <p>Call this method at: After joining a room</>
 *
 * @param callback callback refers to the callback for leave a room.
 */
ZegoRoomManager.getInstance().roomService.leaveRoom(new ZegoRoomCallback() {
   @Override
   public void roomCallback(int errorCode) {
   // Callback for the result of leave a live audio room. 
   }
});

Log out

To finish the Live Audio Room signaling service, call the logout method.

/**
 * User to log out.
 * <p>Description: This method can be used to log out from the current user account.</>
 * <p>Call this method at: After the user login</>
 */
ZegoRoomManager.getInstance().userService.logout();

Deinitialize the zegoliveaudioroom SDK

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

/**
 * The method to deinitialize the SDK.
 * <p> Description: This method can be used to deinitialize the SDK and release the resources it occupies.</>
 * <p> Call this method at: When the SDK is no longer be used. We recommend you call this method when the
 * application exits.</>
 */
ZegoRoomManager.getInstance().unInit();

FAQ

Question: The error Lambda expressions are not supported at language level '7' occurs after importing the zegoliveaudioroom 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
    }
}
Page Directory