logo
On this page

Quick Start Voice Call

This document explains how to quickly integrate the client SDK (ZEGO Express SDK) and achieve voice interaction with an AI Agent.

Prerequisites

  • Contact ZEGOCLOUD technical support to get the version of ZEGO Express SDK that supports AI echo cancellation and integrate it.

Sample Codes

Listed below are the sample codes of core functionalities. You can refer to these sample codes to implement your own business logic.

The following video demonstrates how to run the server and client (Web) sample code and interact with an AI agent by voice.

Overall Business Process

  1. Server side: Follow the Server Quick Start guide to run the server sample code and deploy your server
    • Integrate ZEGOCLOUD AI Agent APIs to manage AI agents.
  2. Client side: Run the sample code
    • Create and manage AI agents through your server.
    • Integrate ZEGO Express SDK for real-time communication.

After completing these two steps, you can add an AI agent to a room for real-time interaction with real users.

sequenceDiagram participant Client participant Your Server participant ZEGOCLOUD AI Agent Server Your Server->>Your Server: Register an AI agent Your Server->>ZEGOCLOUD AI Agent Server: Register an AI agent ZEGOCLOUD AI Agent Server-->>Your Server: Client->>Your Server: Notify server to start call Your Server->>ZEGOCLOUD AI Agent Server: Create an AI agent instance ZEGOCLOUD AI Agent Server->>ZEGOCLOUD AI Agent Server: The AI agent logs into the RTC room, publishes a stream, and plays the user stream ZEGOCLOUD AI Agent Server-->>Your Server: Your Server-->>Client: Client->Your Server: Request Token Your Server-->>Client: Token Client->>Client: Initialize ZEGO Express SDK, login to room and start publishing stream Client->>Client: User plays the AI agent stream Client->>Your Server: Notify server to stop call Your Server->>ZEGOCLOUD AI Agent Server: Delete the AI agent instance ZEGOCLOUD AI Agent Server-->>Your Server: Your Server-->>Client: Client->>Client: User stops publishing the stream and exits the room

Core Capability Implementation

Integrate ZEGO Express SDK

Please refer to Integrate the SDK > 2.2 > Method 2 to manually integrate the SDK. After integrating the SDK, follow these steps to initialize ZegoExpressEngine.

1
Add Permission Declaration

Navigate to the "app/src/main" directory, open the "AndroidManifest.xml" file, and add permissions.

AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" /> 
1
Copied!
2
Request Recording Permission at Runtime
Untitled
private final ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(
    new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
        @Override
        public void onActivityResult(Boolean isGranted) {
            if (isGranted) {
                // Permission granted
            }
        }
    });
// Initiate request
requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO);
1
Copied!
3
Create and Initialize ZegoExpressEngine
Untitled
ZegoEngineProfile zegoEngineProfile = new ZegoEngineProfile();
zegoEngineProfile.appID = ; // Obtain from ZEGOCLOUD Console
zegoEngineProfile.scenario = ZegoScenario.HIGH_QUALITY_CHATROOM; // Setting this scenario can avoid requesting camera permissions, and the integrator should set specific values according to their own business scenarios
zegoEngineProfile.application = getApplication();
ZegoExpressEngine.createEngine(zegoEngineProfile, null);
1
Copied!

Notify Your Server to Start Call

You can notify your server to start the call immediately after the real user enters the room on the client side. Asynchronous calls can help reduce call connection time. After receiving the start call notification, your server creates an AI agent instance using the same roomID and associated userID and streamID as the client, so that the AI agent can interact with real users in the same room through mutual stream publishing and playing.

User logs in a RTC room and starts publishing a stream

After a real user logs into the room, they start publishing streams.

Note

In this scenario, AI echo cancellation should be enabled for better effects.

The token used for login needs to be obtained from your server; please refer to the complete sample code.

Note

Please ensure that the roomID, userID, and streamID are unique under one ZEGOCLOUD APPID.

  • roomID: Generated by the user according to their own rules, it will be used to log into the Express SDK room. Only numbers, English characters, and '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '`', ';', ''', ',', '.', '<', '>', '' are supported. If interoperability with the Web SDK is required, do not use '%'.
  • userID: Length should not exceed 32 bytes. Only numbers, English characters, and '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '`', ';', ''', ',', '.', '<', '>', '' are supported. If interoperability with the Web SDK is required, do not use '%'.
  • streamID: Length should not exceed 256 bytes. Only numbers, English characters, and '-', '_' are supported.
Client login to room and publish a stream
private void loginRoom(String userId, String userName, String userName, String token,
    IZegoRoomLoginCallback callback) {
    ZegoEngineConfig config = new ZegoEngineConfig();
    HashMap<String, String> advanceConfig = new HashMap<String, String>();
    advanceConfig.put("set_audio_volume_ducking_mode", "1");
    advanceConfig.put("enable_rnd_volume_adaptive", "true");
    config.advancedConfig = advanceConfig;
    ZegoExpressEngine.setEngineConfig(config);
    ZegoExpressEngine.getEngine().setRoomScenario(ZegoScenario.HIGH_QUALITY_CHATROOM);
    ZegoExpressEngine.getEngine().setAudioDeviceMode(ZegoAudioDeviceMode.GENERAL);

    ZegoExpressEngine.getEngine().enableAEC(true);
    // Please note: To enable AI echo cancellation, please contact ZEGOCLOUD technical support to obtain the corresponding version of ZEGOExpress SDK
    ZegoExpressEngine.getEngine().setAECMode(ZegoAECMode.AI_AGGRESSIVE2);
    ZegoExpressEngine.getEngine().enableAGC(true);
    ZegoExpressEngine.getEngine().enableANS(true);
    ZegoExpressEngine.getEngine().setANSMode(ZegoANSMode.MEDIUM);

    ZegoRoomConfig roomConfig = new ZegoRoomConfig();
    roomConfig.isUserStatusNotify = true;
    roomConfig.token = token;  // Token authentication is required, obtain it from your server, and refer to ZEGOCLOUD documentation for generation method

    String roomId ;   // Custom room ID for login, please refer to the format description
    String userSteamID // Custom stream ID for publishing, please refer to the format description
    ZegoExpressEngine.getEngine()
        .loginRoom(roomId, new ZegoUser(userId, userName), roomConfig, (errorCode, extendedData) -> {
            Timber.d(
                "loginRoom() called with: errorCode = [" + errorCode + "], extendedData = [" + extendedData + "]");
            if (errorCode == 0) {
                // Start publishing stream after successful login
                ZegoExpressEngine.getEngine().startPublishingStream(userSteamID);
                // Set microphone mute status, false means unmuted, true means muted
                ZegoExpressEngine.getEngine().muteMicrophone(false);
            }
            if (callback != null) {
                callback.onRoomLoginResult(errorCode, extendedData);
            }

        });
}
1
Copied!

Play the AI Agent Stream

By default, there is only one real user and one AI agent in the same room, so any new stream added is assumed to be the AI agent stream.

Client request to play the AI agent stream
// Set up the event handler
void setEventHandler() {
    ZegoExpressEngine.getEngine().setEventHandler(new IZegoEventHandler() {
        @Override
        // When other users in the room start/stop publishing streams, you can receive notifications about the corresponding user's audio/video stream changes here
        public void onRoomStreamUpdate(String roomID, ZegoUpdateType updateType, ArrayList<ZegoStream> streamList, JSONObject extendedData) {
            super.onRoomStreamUpdate(roomID, updateType, streamList, extendedData);
            // When updateType is ZegoUpdateType.ADD, it means there is a new audio/video stream, at this time we can call the startPlayingStream interface to pull this audio/video stream
            if (updateType == ZegoUpdateType.ADD) {
                ZegoStream stream = streamList.get(0);
                // By default, new streams are from the AI agent, so play directly
                ZegoExpressEngine.getEngine().startPlayingStream(stream.streamID);
            }
        }
    });
}
1
Copied!

Congratulations🎉! After completing this step, you can ask the AI agent any question by voice, and the AI agent will answer your questions by voice!

Delete the agent instance and the user exits the room

The client calls the logout interface to exit the room and stops publishing and playing streams. At the same time, it notifies your server to end the call. After receiving the end call notification, your server will delete the AI agent instance, and the AI agent instance will automatically exit the room and stop publishing and playing streams. This completes a full interaction.

Untitled
// Notify your server to end the call
private void stop() {
    RequestBody body = RequestBody.create("", MediaType.parse("application/json; charset=utf-8"));
    Request request = new Request.Builder().url(YOUR_SERVER_URL + "/api/stop").post(body).build();

    new OkHttpClient.Builder().build().newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {

        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            if (response.isSuccessful()) {
                // Exit room
                ZegoExpressEngine.getEngine().logoutRoom();
            }
        }
    });
}

1
Copied!

This is the complete core process for you to achieve real-time voice interaction with an AI agent.

Previous

Release Notes

Next

Display Subtitles