DEV Community

Stephen568hub
Stephen568hub

Posted on

How to Build a Live Streaming App for Android

Have you watched live videos on social media or played an online game before? If you have done them, you’ve probably consumed live streaming technology. Live streaming provides an interface for us to share video from a central position and distribute it to other users efficiently in the form of streams.

In this article, I will walk you through what live streaming is, and how to build an Android live streaming app using ZEGOCLOUD’s Live SDK.

What is a Live Streaming API/SDK?

Live streaming SDK and API providers make it possible for companies and individuals to build software applications, mobile apps, websites, and web apps that can stream live video and audio.

Live streaming SDK offers comprehensive developer toolkits and components like WebRTC that make it easy to build custom live streaming platforms into web and mobile apps. Live video streaming platforms, virtual event platforms, video conferencing and video calling apps, and more can all use live streaming SDK and APIs.

ZEGOCLOUD’s Zego Live SDK is a good example of live streaming SDK. You can build production-grade live streaming apps using this SDK with minimal configuration. You’ll be amazed to see how easy it’s to integrate Zego Live into your app and using its video and audio cloud streaming infrastructures.

ZEGOCLOUD as well provide 10000 free minutes, so you can take advantage of it to build free live streams.

The main reason live streaming SDK exist is mainly to simplify the setup for you and enable you to launch your live apps with spending much on infrastructure setup, and coding everything from scratch. You can spend weeks or even months in building live streaming apps from scratch depending on you programming prowess or that of the development team. The story is completely different with live streaming SDK, as you can do so in minutes. Interesting, isn’t?

In the next section, we’ll look at various types of live streaming.

Types of Live Streaming Apps

Several types of live streaming apps exist and more is likely to enter the app market as the technology is booming right now. While many live streaming apps exist, we can still categorize them based on what they’re used for and their core functionality.

Without further ado, below are some popular types of live streaming apps.

1. Audio live streaming

This is among the most common usage of live streaming technology. This type of live streaming app allows the transmission of audio data from central storage to multiple users as per configurations. If you have used Apple music, Pandora, and even spotify, then you have used an audio live streaming app before!

2. Real-time broadcasting apps

Have you watched live videos on youtube? Or play some used facebook live features before? If you’ve done any of of the listed, then you’ve used live streaming feature for real-time broadcasting. This type of live streaming is very popular, owing to the fact that millions of people use Youtube, Facebook, and even Tik Tok on daily basis. I’m very convinced that you reading this article have used it as well!

3. Live TV Streaming Applications

Live streaming television, which requires a paid subscription, enables users to view the most recent episode of their favorite show or game as it airs in real time. Some examples includes Hulu, Youtube TV, and so on.

4. Video on demand

The term "video on demand" refers to a media distribution method that enables viewers to watch videos without the need for a conventional video playback device or the restrictions imposed by a standard, unchanging programming schedule.

How to Make Android Live Stream App with Zego Live API/SDK

We have been talking about live streaming SDK and API all these while, but “how exactly do I set up my live streaming app using them?”. This section will clear all your doubts about building live streaming apps. We’ll be using ZEGOCLOUD’s Zego Live to create free live streams. You’ll learn more about Zego Live SDK as we progress with the sections.

Zego Live SDK Introduction

ZEGO Live, also known as the Express-Video Software Development Kit, is a tool that can assist developers in rapidly integrating interactive live video streaming and video calling capabilities into mobile, desktop, and web applications for a wide variety of use cases. Some examples of these use cases include one-on-one and group video calls, online education, and entertainment live video streaming.

Your applications will be able to gain access to ZEGOCLOUD's cloud streaming platform in just four easy steps. This will allow your applications to deliver high-quality, ultra-low-latency, and interactive video to your end-users across all platforms. In addition, massive concurrency will be supported, giving users the opportunity to enjoy a perfect live video experience.

Why Use Zego Live SDK?

You may be wondering why you need to use Zego Live SDK in building your live streaming apps.

Below are some of the reasons:

1. Multiple live engagement modes

In order to cater to the requirements of a variety of live interaction scenarios, you should develop single-host, multi-host, and cross-room co-hosted live streaming sessions.

2. Superior audio and video quality

Stream high-quality live video with a resolution of 4K and audio that is incredibly clear live with a sample rate of 48kHz throughout the full band.

3. Support for massively parallel processing

By integrating a single software development kit (SDK), you can gain access to the capacity of live streaming to an audience of tens of millions of people as well as all of the building blocks you need to produce full-featured live streaming.

4. Detailed effects in both audio and video

Face enhancing software, speech enhancing software, musical accompaniments, and a wide variety of additional audio and video effects can make live streaming a more enjoyable and interactive experience.

5. Processing of all forms of streaming material

Create the live streaming application that best meets your requirements by making use of a comprehensive set of streaming media processing functions. These features include stream mixing, recording, snapshotting, super resolution, and many more.

6. connections that are seamless and have an extremely low latency

Users located all over the world can receive live audio and video feeds, as well as instant messages, with an extremely low latency from beginning to end.

Preparation

  • ZEGOCLOUD Admin Console account--Sign up
  • Android device or AVD with version 5.0 and above, with support for video and audio.
  • Recent version of Android studio.
  • A basic understanding of Android app development.

Zego Live SDK Integration

Create a project**

Follow the steps below to create an app in Android studio.

Follow the steps below to create a project on Android studio:

  1. Click on FileNewNew project in Android Studio's menu bar.

  2. Enter application name in “Application name” and choose place to save your new project in “Project location”.

  3. Leave the default settings, click Next, and then Finish.

Import SDK

To incorporate Zego Live SDK into the project that we have created, follow the steps below:

  1. If you are using Android Gradle Plugin version 7.1.0 or a later version: Find the file named settings.gradle in the root directory of the project, open it, and then paste the following code into the dependent ResolutionManagement section:
...
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        maven { url 'https://jitpack.io' }
        google()
        mavenCentral()
    }
}
Enter fullscreen mode Exit fullscreen mode
  • If the version of the Android Gradle Plugin you're using is older than 7.1.0, the following applies to you: Open the build.gradle file that is located in the root of your project, and add the following lines of code to the allprojects section:
...
allprojects {
    repositories {
        maven { url 'https://www.jitpack.io' }
        google()
        mavenCentral()
    }
}
Enter fullscreen mode Exit fullscreen mode
  • You will not be able to find the aforementioned fields in gradle.settings if the version of the Android Gradle Plugin you are using is older than v7.1.0..
  1. Modify build.gradle file in your app directory and add the following codes to the dependencies section. To get the recent version number, visit ZEGO Express-Video Android SDK Release History and enter "x.y.z" where "x.y.z" is the SDK version number.
...
dependencies {
    ...
    implementation 'com.github.zegolibrary:express-video:2.+'
}
Enter fullscreen mode Exit fullscreen mode

Add permissions

Follow the steps below to request for permission to access device resources.

  1. The AndroidManifest.xml file that can be found in the app's source folder has to have the following line of code added to it, in order to request for permission:
<!-- 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" />

<!-- Permissions required by the App -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Enter fullscreen mode Exit fullscreen mode

Prevent class name obfuscation

The obfuscation of the public class names in the ZEGO SDK can be disabled by inserting the code that is presented in this article into the proguard-rules.pro file.

-keep class **.zego.**{*;}
Enter fullscreen mode Exit fullscreen mode

Implement a Basic Live Streaming

Before we move forward with the process of implementing a basic live streaming. You will need to familiarize yourself with some fundamental ideas in order to comprehend how Zego Live SDK renders video and audio. The following are the fundamental ideas:

  • The client application will take audio and video streams and then publish them to the ZEGO Real-Time Audio and Video Cloud as part of the process known as stream publishing.
  • When a client application retrieves audio and video streams from the ZEGO Real-Time Audio and Video Cloud in order to play them, this is an example of stream playing.
  • Room is a group-organizing tool that enables users to share and receive real-time audio, video, and text messages with other individuals who are in the same room with them. Before you are able to play or publish a stream, you will need to first log in to the room. Users will only receive notifications about changes made to the room they are currently members to.

In light of this, the following diagram illustrates what takes on when User A plays a stream that User B originally submitted.

live free streaming

Follow the steps below to implement a basic live streaming app using Zego Live SDK:

Create a ZegoExpressEngine instance

Calling the createEngine function of the ZegoExpressEngine class with the AppID of your project as an argument will allow you to create a singleton instance of that class.

//  Create a ZegoExpressEngine instance and set eventHandler to [self]. 
// If eventHandler is set to [null], no callback will be received. You can set up the event handler later by calling the [setEventHandler:] method.
ZegoEngineProfile profile = new ZegoEngineProfile();
profile.appID = ;  // The AppID you get from ZEGOCLLOUD Admin Console. AppID format: 123456789L
profile.appSign = ;  // The AppSign you get from ZEGOCLOUD Admin Console. AppSign format: @"0123456789012345678901234567890123456789012345678901234567890123" (64 characters)
profile.scenario = ZegoScenario.GENERAL;  // Use general scenario.
profile.application = getApplication();
engine = ZegoExpressEngine.createEngine(profile, null);
Enter fullscreen mode Exit fullscreen mode

Log in to a room

Use the loginRoom function to sign in to a room. When you use the loginRoom method, a new room will be established if the specified roomID does not already exist, and you will be automatically logged in to the newly created room.

/** create a user **/
ZegoUser user = new ZegoUser("user1");


ZegoRoomConfig roomConfig = new ZegoRoomConfig();
/** 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";
/** onRoomUserUpdate callback can be received only by passing in a ZegoRoomConfig whose "isUserStatusNotify" parameter value is "true".*/
roomConfig.isUserStatusNotify = true;

/** log in to a room */
engine.loginRoom("room1", user, roomConfig, (int error, JSONObject 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.
});  
Enter fullscreen mode Exit fullscreen mode

Implement the event callback methods of the event handler to listen for and handle various events after logging into a room. Common room user and stream event callbacks includes:

  • onRoomStateUpdate: Callback for room connection updates. The SDK sends this callback when the current user's room connection status changes (for example, when the user is disconnected or login authentication fails).
  • onRoomUserUpdate: Updates on room users. This callback notifies the SDK when users join or depart the room.
  • onRoomStreamUpdate: Updates room streams. The SDK sends this callback when new streams are published to the room or stopped.
engine.setEventHandler(new IZegoEventHandler() {

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

    /** Callback for updates on the current user's room connection status. */
    @Override
    public void onRoomStateUpdate(String roomID, ZegoRoomState state, int errorCode, JSONObject extendedData) {
        /** Implement the callback handling logic as needed. */
    }

    /** Callback for updates on the status of other users in the room. */
    @Override
    public void onRoomUserUpdate(String roomID, ZegoUpdateType updateType, ArrayList<ZegoUser> userList) {
        /** Implement the callback handling logic as needed. */
    }

    /** Callback for updates on the status of the streams in the room. */
    @Override
    public void onRoomStreamUpdate(String roomID, ZegoUpdateType updateType, ArrayList<ZegoStream> streamList, JSONObject extendedData){
        /** Implement the callback handling logic as needed. */
     }

});
Enter fullscreen mode Exit fullscreen mode

Start the local video preview

Call startPreview using the local video view's canvas parameter to start the local video preview.

/**
 *  Set up a view for the local video preview and start the preview with SDK's default view mode (AspectFill).
 *  The following play_view is a SurfaceView, TextureView, or SurfaceTexture object on the UI.
 */
engine.startPreview(new ZegoCanvas(preview_view));
Enter fullscreen mode Exit fullscreen mode

Publish streams

Call startPublishingStream with the streamID parameter to publish a local audio or video stream to remote users.

/** Start publishing a stream */
engine.startPublishingStream("stream1");
Enter fullscreen mode Exit fullscreen mode

Play streams

To play a remote audio or video stream, call startPlayingStream with the streamID and canvas parameters.

/**
 *  Start playing a remote stream with the SDK's default view mode (AspectFill).
 *  The play_view below is a SurfaceView/TextureView/SurfaceTexture object on UI.
 */
engine.startPlayingStream("stream1", new ZegoCanvas(play_view));
Enter fullscreen mode Exit fullscreen mode

Callback:

engine.setEventHandler(new IZegoEventHandler() {
    /** Common event callbacks related to stream playing. */

    /** Callback for updates on stream playing status.  */
    @Override
    public void onPlayerStateUpdate(String streamID, ZegoPlayerState state, int errorCode, JSONObject extendedData){
        /** Implement the callback handling logic as needed. */
    }
});
Enter fullscreen mode Exit fullscreen mode

Stop publishing streams

Simply using the stopPublishingStream function will put an end to any local audio or video streams being broadcast to remote users.

/** Stop publishing a stream */
engine.stopPublishingStream();
Enter fullscreen mode Exit fullscreen mode

Call stopPreview to stop local video preview.

/** Stop local video preview */
engine.stopPreview();
Enter fullscreen mode Exit fullscreen mode

Log out of a room

Call logoutRoom with the room ID to log out.

/** Log out of a room */
engine.logoutRoom("room1");
Enter fullscreen mode Exit fullscreen mode

Destroy the ZegoExpressEngine instance

Call the destroyEngine method to get rid of the ZegoExpressEngine instance and free up the resources it uses.

/** Destroy the ZegoExpressEngine instance */
ZegoExpressEngine.destroyEngine(null);
Enter fullscreen mode Exit fullscreen mode

Run a demo.

Conclusion

The Zego Live SDK removes the difficulty in creating live streaming applications, by compressing complex programming concepts into friendly APIs that can be called to get things done. From the steps we covered so far, you can see that it is extremely very easy to live stream free using ZEGOCLOUD’s Zego Live SDK.

If you want to make audio and video apps, you can download the sample demo source code from this article.

We offer technical support around the clock, so feel free to call us whenever you need help.

Read More
How To Build a Flutter Live Streaming App
How To Build an iOS Live Streaming App
How To Build an Android Live Streaming App
How To Build React Native Live Streaming App

Top comments (0)