Live Streaming
  • iOS : Objective-C
  • Android
  • Web
  • Flutter
  • React Native
  • Electron
  • Unity3D
  • Windows
  • macOS
  • Linux
  • Overview
  • Live Streaming vs. Interactive Live Streaming
  • Develop your app
    • Live Streaming
      • Integrate the SDK
      • Implement a basic live streaming
      • Enhance basic livestream
      • CDN
      • Play live streams
    • Interactive Live Streaming
  • Upgrade the livestream
    • Advanced features
      • Media push
        • Mix the live streams
      • Enhance the livestream
        • Share the screen
        • Improve your appearance in the livestream
        • Beautify & Change the voice
        • Output the livestream in H.265
        • Watermark the live/Take snapshots
        • Config video codec
        • Visualize the sound level
      • Message signaling
        • Convey extra information using SEI
        • Broadcast real-time messages to a room
        • Quotas and limits
      • Ensure livestream quality
        • Test network and devices in advance
        • Check the room connection status
        • Monitor streaming quality
        • Configure bandwidth management
      • Play media files
        • Play media files
        • Play sound effects
      • Record video media data
      • Join multiple rooms
      • Publish multiple live streams
      • Low-latency live streaming
      • Use the bit mask
      • Common audio config
      • Playing streams via URL
    • Distincitve features
      • Set the voice hearing range
      • Single stream transcoding
      • Low-light enhancement
      • Customize the video and audio
  • Upgrade using Add-on
  • Resources & Reference
    • SDK
    • Sample code
    • API reference
      • Client APIs
      • Server APIs
    • Debugging
      • Error codes
    • FAQs
    • Key concepts
  • Documentation
  • Live Streaming
  • Develop your app
  • Live Streaming
  • Implement a basic live streaming

Implement a basic live streaming

Last updated:2023-05-17 19:58

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 ZEGO 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 ZEGO Real-Time Audio and Video Cloud.

  • Stream playing: The process of the client app receiving and playing audio and video streams from the ZEGO 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 Integration.

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 Upgrade guide.

Implementation process

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

First, import the header file ZegoExpressEngine.h into the project.

// Import the header file ZegoExpressEngine.h 
#import <ZegoExpressEngine/ZegoExpressEngine.h>

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

To receive callbacks, implement an event handler object that conforms to the ZegoEventHandler protocol(for example, self), and then pass the implemented event handler object to the createEngineWithProfile method as the eventHandler parameter. Alternatively, you can pass nil to the createEngineWithProfile method as the eventHandler parameter for now, and then call the method setEventHandler to set up the event handler after creating the engine.

/**
*  appID: The AppID value you get from the ZEGOCLOUD Admin console.
*  The AppID ranges from 0 - 4294967295.
* appSign: The AppSign you get from the ZEGOCLOUD Admin console.
* scenario: the scenario you use. [ZegoScenarioGeneral] refers to the general scenario. 
*/
ZegoEngineProfile *profile = [[ZegoEngineProfile alloc] init];
profile.appID = <#appID#>;
profile.appSign = <#appSign#>;
profile.scenario = ZegoScenarioGeneral;
// Create a ZegoExpressEngine instance and set eventHandler to [self]. If eventHandler is set to [nil], no callback will be received. You can set up the event handler later by calling the [-setEventHandler:] method.
[ZegoExpressEngine createEngineWithProfile:profile eventHandler:self];

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 user
ZegoUser *user = [ZegoUser userWithUserID:@"user1"];

ZegoRoomConfig *roomConfig = [[ZegoRoomConfig alloc] init];
// 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 = @"xxxxx";
// onRoomUserUpdate callback can be received only by passing in a ZegoRoomConfig whose "isUserStatusNotify" parameter value is "true".
roomConfig.isUserStatusNotify = YES;
// log in to a room
[[ZegoExpressEngine sharedEngine] loginRoom:roomID user:user config:roomConfig callback:^(int errorCode, NSDictionary * _Nullable extendedData) {
    // (Optional callback) The result of logging in to the room. If you only pay attention to the login result, you can use this callback.
}];

Then, to listen for and handle various events that may happen after logging in to a room, you can implement the corresponding event callback methods of the event handler as needed. The following are some common event callbacks related to room users and streams:

  • onRoomStateUpdate: Callback for updates on current user's room connection status. When the current user's room connection status changes (for example, when the current user is disconnected from the room or login authentication fails), the SDK sends out the event notification through this callback.

  • onRoomUserUpdate: Callback for updates on the status of other users in the room. When other users join or leave the room, the SDK sends out the event notification through this callback.

  • onRoomStreamUpdate: Callback for updates on the status of the streams in the room. When new streams are published to the room or existing streams in the room stop, the SDK sends out 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 you call the loginRoom method to log in to a room.
  • To play streams published by other users in the room: you can listen for the onRoomStreamUpdate callback, and when there is a stream added, call the startPlayingStream method to start receiving and playing the newly added stream.
// Conform to the ZegoEventHandler protocol to handle event callbacks
@interface ViewController () <ZegoEventHandler>
// ······
@end

@implementation ViewController

// Common event callbacks related to room users and streams.

// Callback for updates on the current user's room connection status.
- (void)onRoomStateUpdate:(ZegoRoomState)state errorCode:(int)errorCode extendedData:(nullable NSDictionary *)extendedData roomID:(NSString *)roomID {
    // Implement the callback handling logic as needed. 
}

// Callback for updates on the status of other users in the room.
// Users can only receive callbacks when the isUserStatusNotify property of ZegoRoomConfig is set to `true` when logging in to the room (loginRoom).
- (void)onRoomUserUpdate:(ZegoUpdateType)updateType userList:(NSArray<ZegoUser *> *)userList roomID:(NSString *)roomID {
    // Implement the callback handling logic as needed. 
}

// Callback for updates on the status of the streams in the room.
- (void)onRoomStreamUpdate:(ZegoUpdateType)updateType streamList:(NSArray< ZegoStream * > *)streamList extendedData:(nullable NSDictionary *)extendedData roomID:(NSString *)roomID {
    // Implement the callback handling logic as needed. 
    // If users want to play the streams published by other users in the room, call the startPlayingStream method with the corresponding streamID obtained from the `streamList` parameter where ZegoUpdateType == ZegoUpdateTypeAdd.
}

@end

Start the local video preview

To start the local video preview, call the startPreview method with the view for rendering the local video passed to the canvas parameter.

// Set up a view for the local video preview and start the preview with SDK's default view mode (AspectFill).
[[ZegoExpressEngine sharedEngine] startPreview:[ZegoCanvas canvasWithView:self.view]];

Publish streams

To start publishing a local audio or video stream to remote users, call the startPublishingStream method with the corresponding stream ID passed to the streamID parameter.

streamID 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.

// Start publishing a stream
[[ZegoExpressEngine sharedEngine] startPublishingStream:@"stream1"];

Then, to listen for and handle various events that may happen after stream publishing starts, you can implement the corresponding event callback methods of the event handler as needed. The following is a common event callback related to stream publishing:

  • onPublisherStateUpdate: Callback for updates on stream publishing status. 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), the SDK sends out the event notification through this callback.
// Conform to the ZegoEventHandler protocol to handle event callbacks
@interface ViewController () <ZegoEventHandler>
// ······
@end

@implementation ViewController

// Common event callbacks related to stream publishing.

// Callback for updates on stream publishing status.  
- (void)onPublisherStateUpdate:(ZegoPublisherState)state errorCode:(int)errorCode extendedData:(nullable NSDictionary *)extendedData streamID:(NSString *)streamID {
    // Implement the callback handling logic as needed. 
}

@end

Play streams

To start playing a remote audio or video stream, call the startPlayingStream method with the corresponding Stream ID passed to the streamID parameter and the view for rendering the video passed to the canvas parameter.

You can obtain the stream IDs of the streams published by other users in the room from the callback onRoomStreamUpdate.

// Play a remote stream
[[ZegoExpressEngine sharedEngine] startPlayingStream:@"stream1" canvas:[ZegoCanvas canvasWithView:self.view]];

Then, to listen for and handle various events that may happen after stream playing starts, you can implement the corresponding event callback methods of the event handler as needed. The following is a common event callback related to stream playing:

  • onPlayerStateUpdate: Callback for updates on stream playing status. 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), the SDK sends out the event notification through this callback.
// Conform to the ZegoEventHandler protocol to handle event callbacks
@interface ViewController () <ZegoEventHandler>
// ······
@end

@implementation ViewController

// Common event callbacks related to stream playing.

// Callback for updates on stream playing status. 
- (void)onPlayerStateUpdate:(ZegoPlayerState)state errorCode:(int)errorCode extendedData:(NSDictionary *)extendedData streamID:(NSString *)streamID {
    // Implement the callback handling logic as needed. 
}

@end

Test out the function

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 and playing streams

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

// Stop publishing a stream
[[ZegoExpressEngine sharedEngine] stopPublishingStream];

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

// Stop local video preview
[[ZegoExpressEngine sharedEngine] stopPreview];

To stop playing a remote audio or video stream, call the stopPlayingStream method with the corresponding stream ID passed to the streamID parameter.

// Stop playing a stream
[[ZegoExpressEngine sharedEngine] stopPlayingStream:@"stream1"];

Log out from a room

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

// Log out of a room
[[ZegoExpressEngine sharedEngine] logoutRoom:@"room1"];

Destroy the ZegoExpressEngine instance

To destroy the ZegoExpressEngine instance and release the resources it occupies, call the destroyEngine method.

  • 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 nil to destroyEngine instead.
[ZegoExpressEngine destroyEngine:nil];

API call sequence diagram

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

/Pics/QuickStart/quickstart_uml_en_detail.png

Page Directory