Documentation
ExpressVideoSDK Video Call
Documentation
Demo APP
SDK Center
API Center
FAQ
Code Market
Console
Sign Up
Log In
中文站 English
  • Documentation
  • Video Call
  • Develop your app
  • Implement a basic video call

Implement a basic video call

Last updated:2024-12-04 15:52

Introduction

This guide describes how to implement basic audio and video functions with the ZEGO Express SDK.

Basic concepts:

  • ZEGO Express SDK: The real-time audio and video SDK developed by ZEGOCLOUD to help you quickly build high-quality, low-latency, and smooth real-time audio and video communications into your apps across different platforms, with support for massive concurrency.

  • Stream publishing: The process of the client app capturing and transmitting audio and video streams to the ZEGOCLOUD Real-Time Audio and Video Cloud.

  • Stream playing: The process of the client app receiving and playing audio and video streams from the ZEGOCLOUD Real-Time Audio and Video Cloud.

  • Room: The service for organizing groups of users, allowing users in the same room to send and receive real-time audio, video, and messages to each other.

    1. Logging in to a room is required to perform stream publishing and playing.
    2. Users can only receive notifications about changes in the room they are in (such as new users joining the room, existing users leaving the room, new audio and video streams being published, etc.).

For more basic concepts, refer to the Glossary.

Prerequisites

Before you begin, make sure you complete the following steps:

  • Create a project in ZEGOCLOUD Console, and get the AppID and AppSign of your project.
  • The ZEGO Express SDK has been integrated into the project. For details, see How to view project information.

If the version of the ZEGO Express SDK you are using is under 2.17.0, to get the AppSign, contact the ZEGOCLOUD Technical Support. To upgrade the authentication mode from using the AppSign to Token, see Guide for upgrading the authentication mode from using the AppSign to Token.

Implementation steps

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

/Pics/Common/ZegoExpressEngine/implementation_overall.png

The following sections explain each step of this process in more detail.

Create a ZegoExpressEngine instance

1. Create the UI

Before creating a ZegoExpressEngine instance, we recommend you add the following UI elements to implement basic real-time audio and video features:

  • A view for local preview
  • A view for remote video
  • An End button

/Pics/Common/ZegoExpressEngine/express_quickstart_video_call_pc_EN.png

2. Import the header file

Import the header file ZegoExpressSDK.h into the project.

// Import the header file ZegoExpressEngine.h
#include "ZegoExpressSDK.h"

3. Create a ZegoExpressEngine instance

To create a singleton instance of the ZegoExpressEngine class, call the createEngine method with the AppID of your project.

To receive callbacks, implement an event handler object that conforms to the IZegoEventHandler protocol, and then pass the implemented event handler object as the eventHandler parameter. Alternatively, you can pass nullptr as the eventHandler parameter for now, and then call the method setEventHandler to set up the event handler after creating the engine.


ZegoEngineProfile profile;
profile.appID = appID;
profile.scenario = ZegoScenario::ZEGO_SCENARIO_GENERAL;
// Create a ZegoExpressEngine instance.
auto engine = ZegoExpressSDK::createEngine(profile, nullptr);

Log in to a room

Before logging in to a room, you will need to generate a token first; Otherwise, the login will fail.
To generate a token, refer to the Use Tokens for authentication.

To log in to a room, call the loginRoom method. If the roomID does not exist, a new room will be created and you will log in automatically when you call the loginRoom method.

// Create a ZegoUser object. 
ZegoUser user("user1", "user1");

ZegoRoomConfig roomConfig;
// Token is generated by the user's own server. For an easier and convenient debugging, you can get a temporary token from the ZEGOCLOUD Admin Console
roomConfig.token = "xxxx";
// To receive the onRoomUserUpdate callback, you must set the [isUserStatusNotify] property of the room configuration parameter [ZegoRoomConfig] to [true].
roomConfig.isUserStatusNotify = true;
// Log in to a room.
engine->loginRoom(roomID, user, roomConfig, [=](){
    // (Optional callback) The result of logging in to the room. If you only pay attention to the login result, you can use this callback.
});

To monitor your room connection status in real time after making a method call to log in to a room, listen for onRoomStateUpdate callback.

You can only start publishing streams (startPublishingStream) or playing streams (startPlayingStream) when the room state is connected.

void VideoTalk::onRoomStateUpdate(const std::string &roomID, ZegoRoomState state, int errorCode, const std::string &extendData) {
    if(errorCode != 0)
    {
        // Room state error.
    }
    if(state == ZegoRoomState::ZEGO_ROOM_STATE_CONNECTED)
    {
        // You can only perform the stream publishing (startPublishingStream) and stream playing (startPlayingStream) operations when the room state is connected. 
        //Publish your audio and video streams to the ZEGO Real-Time Audio and Video Cloud. 
    }
    else if (state == ZegoRoomState::ZEGO_ROOM_STATE_CONNECTING)
    {
        // Connecting to the room.
    } else if (state == ZegoRoomState::ZEGO_ROOM_STATE_DISCONNECTED)
    {
        // Room get disconnected.
    }
}

Start local video preview

To start the local video preview, call the startPreview method to set the canvas for the video preview, and enable the local video preview.

// Set the canvas for the local video preview, and enable the local video preview. The SDK uses the default view (Fill in the window handle of Windows).
ZegoCanvas canvas((void*)view);
engine->startPreview(&canvas);

Publish streams

To publish the audio and video streams to the ZEGO Real-Time Audio and Video Cloud after logging in to a room, call the startPublishingStream method with the corresponding stream ID passed to the streamID parameter.

You can generate the streamID as needed, but make sure it meets the requirement: It must be globally unique within the scope of the AppID. If different streams are published with the same streamID, the ones that are published after the first one will fail.

You have not restricted to only publishing the streams immediately after logging in to a room, you can also publish the streams at other times as long as the room state is Connected.

void VideoTalk::onRoomStateUpdate(const std::string &roomID, ZegoRoomState state, int errorCode, const std::string &extendData) {
    if (state == ZegoRoomStateConnected) {
            // Room connected successfully.
            // You can only perform stream publishing, stream playing, and other operations when the room state is connected.
            // Publish the audio and video streams to the ZEGO Real-Time Audio and Video Cloud.
            engine->startPublishingStream("stream1");
     }
}

Play streams

To play the audio and video streams of other users during a video call, refer to the following:

  1. You receive an event notification through the callback onRoomStreamUpdate when there are new streams are published to the ZEGO Real-Time Audio and Video Cloud.

  2. After receiving the event notifications, you can call the startPlayingStream method in the callback with the corresponding stream ID passed to the streamID parameter to play the audio and video streams of other users.

For errors occurred during a video call, refer to the Error codes.

// You will receive a event notification on here when new streams are published to the room or existing streams in the room stop.
void VideoTalk::onRoomStreamUpdate(const std::string &roomID, ZegoUpdateType updateType, const std::vector<ZegoStream> &streamList, const std::string &extendData) {
    //When [updateType] is [ZEGO_UPDATE_TYPE_ADD], indicating new stream is published to the room, at this time, you can call the [startPlayingStream] method to play the new audio or video stream. 
    if (updateType == ZEGO_UPDATE_TYPE_ADD) {
        // To start playing a stream, set the canvas for the remote rendering view (The SDK uses the default view, that is, fill in the window handle of Windows). 
        // The [playView] is the window handle of the UI. 
        std::string streamID = streamList[0].streamID;
        ZegoCanvas canvas((void*)playView);
        engine->startPlayingStream(streamID , &canvas);
    }
}

Test out the video call

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.

Common event callbacks

Callback for updates on your room connection status

onRoomStateUpdate: To monitor your room connection status in real time, listen for this callback when calling the loginRoom method to log in to a room.

You can implement the callback handling logic based on the actual room state.

void VideoTalk::onRoomStateUpdate(const std::string &roomID, ZegoRoomState state, int errorCode, const std::string &extendData) {

}

The following shows the implications of the ZegoRoomState state:

State Enumerated value Implication
ZEGO_ROOM_STATE_DISCONNECTED
0
Disconnected state, which appears before you log in to a room or after you log out from a room. This state also appears if a steady-state exception occurs during the login operation, for example, the AppID and token are incorrect, or the local end user is kicked out when the same username is used to log in to another rooms.
ZEGO_ROOM_STATE_CONNECTING
1
Connecting state, which appears when you perform the room login operation successfully. (Generally, the user can set a corresponding UI to indicate the current state.) This state also appears when the SDK automatically tries to reconnect when users disconnected from a room due to network errors.
ZEGO_ROOM_STATE_CONNECTED
2
Connected state, which appears when you log in to a room successfully. In this state, users can receive event notifications related to room users and streams.

Callback for updates on the status of other users in the room

onRoomUserUpdate: When other users join or leave the room, you will receive the event notification through this callback.

  • To receive the onRoomUserUpdate callback, you must set the isUserStatusNotify property of the room configuration parameter ZegoRoomConfig to true when calling the loginRoom method to log in to a room.
  • When the ZegoUpdateType is ZEGO_UPDATE_TYPE_ADD: indicates new users join the room. When the ZegoUpdateType is ZEGO_UPDATE_TYPE_DELETE: indicates other users leave the room.
void VideoTalk::onRoomUserUpdate(const std::string &roomID, ZegoUpdateType updateType, const std::vector<ZegoUser> &userList) {
    // You can implement the callback handling logic based on the actual situation (users join/leave the room). 
    if (updateType == ZEGO_UPDATE_TYPE_ADD) {

    } else if (updateType == ZEGO_UPDATE_TYPE_DELETE) {

    }
}

Callback for updates on stream publishing status

onPublisherStateUpdate: After stream publishing starts, if the status changes, (for example, when the stream publishing is interrupted due to network issues and the SDK retries to start publishing the stream again), you will receive the event notification through this callback.

void VideoTalk::onPublisherStateUpdate(const std::string &streamID, ZegoPublisherState state, int errorCode, const std::string &extendData) {
    if (errorCode != 0) {
        // Error publishing streams. 
    } else {
        switch (state) {
            case ZEGO_PUBLISHER_STATE_PUBLISHING:
                // Stream is being published.
                break;
            case ZEGO_PUBLISHER_STATE_PUBLISH_REQUESTING:
                // Requesting the stream publishing operation. 
                break;
            case ZEGO_PUBLISHER_STATE_NO_PUBLISH:
                // No stream is being published.
                break;
        }
    }
}

Callback for updates on stream playing status

onPlayerStateUpdate: After stream playing starts, if the status changes (for example, when the stream playing is interrupted due to network issues and the SDK retries to start playing the stream again), you will receive the event notification through this callback.

void VideoTalk::onPlayerStateUpdate(const std::string &streamID, ZegoPlayerState state, int errorCode, const std::string &extendData) {
    if (errorCode != 0) {
        //Error playing the stream.
    } else {
        switch (state) {
            case ZEGO_PLAYER_STATE_NO_PLAY:
                // Stream is being played.
                break;
            case ZEGO_PLAYER_STATE_PLAY_REQUESTING:
                // Requesting the stream playing operation. 
                break;
            case ZEGO_PLAYER_STATE_NO_PLAY:
                // No stream is being played
                break;
        }
    }
}

Stop publishing streams

To stop publishing a local audio or video stream to remote users, call the stopPublishingStream method.

// Stop publishing a stream.
engine->stopPublishingStream();

If local video preview is started, call the stopPreview method to stop it as needed.

// Stop the local video preview.
engine->stopPreview();

Stop playing streams

To stop playing a remote audio or video stream, call the stopPlayingStream method.

// Stop playing a stream.
engine->stopPlayingStream("streamID");

Log out

To log out of a room, call the logoutRoom method with the corresponding room ID passed to the roomID parameter.

// Log out from a room.
engine->logoutRoom("room1");

Destroy the ZegoExpressEngine instance

To destroy the ZegoExpressEngine instance and release the microphone, camera, memory, CPU, and other resources it occupies, call the destroyEngine.

  • If you want to receive a callback to make sure the hardware resources are released, pass in the value callback when destroying the ZegoExpressEngine instance. This callback can only be used to send out a notification when the destruction of the engine is completed. You can't use this callback method to release engine-related resources.
  • If you don't want to receive any callbacks, pass nullptr to destroyEngine instead.
// Destroy a ZegoExpressEngine instance.
ZegoExpressSDK::destroyEngine(engine, nullptr);

FAQ

1. Can I kill the process immediately after calling the logoutRoom method to log out from a room?

If you have done so, which may possibly cause the signaling of the logoutRoom method call to fail to be sent. In this case, the ZEGO server does not determine that the user has logged out of the room until the heartbeat times out.

To make sure the signaling of the logoutRoom method call be sent successfully, we recommend you call the destroyEngine method and kill the process after you received the event notifications.

Related documents

  • How can I obtain the SDK logs and stack traces?
  • Does ZEGO SDK support a fast reconnection for temporary disconnection?
  • How can I listen for the event callbacks related to room users' login/logout in live streaming??

The following diagram shows the API call sequence of the stream publishing and playing process:

/Pics/QuickStart/quickstart_uml_en_detail.png

Page Directory
  • Free trial
  • 提交工单
    咨询集成、功能及报价等问题
    电话咨询
    400 1006 604
    Get Consulting
    Scan Wechat QR code