Skip to main content
Version: 3.x.x

Initialize Live Stream - Android

To configure livestreaming with VideoSDK, you need two things: a token for Authentication, and a streamId that specifies where the hosts and audience join.

Generating Token​

You can generate a token in two ways:

  1. Temporary Token : You can visit Dashboard's API Key section and generate a temporary token from there.

  2. Server : You can set up JWT in your backend and make an API call to get the token from your server.

To learn more about Authentication and token in detail you can follow this guide.

With Temporary Token
fun getToken(): String {
// Update the token here from the VideoSDK dashboard
return "YOUR_TOKEN"
}
Server
suspend fun getToken(): String = withContext(Dispatchers.IO) {
val request = Request.Builder()
.url("https://YOUR_TOKEN_SERVER/get-token") // your token server's endpoint
.build()
OkHttpClient().newCall(request).execute().use { response ->
val body = response.body?.string().orEmpty()
check(response.isSuccessful) { "HTTP ${response.code}: $body" }
JSONObject(body).getString("token")
}
}

Generating Stream Id​

With the token ready, you can now get the streamId from the VideoSDK's rooms API.

suspend fun getStreamId(token: String): String = withContext(Dispatchers.IO) {
// We will use VideoSDK rooms API endpoint to create a streamId
val request = Request.Builder()
.url("https://api.videosdk.live/v2/rooms")
.header("Authorization", token) // We will pass the token in the headers
.post("".toRequestBody())
.build()
OkHttpClient().newCall(request).execute().use { response ->
val body = response.body?.string().orEmpty()
check(response.isSuccessful) { "HTTP ${response.code}: $body" }
//we will return the streamId which we got from the response of the api
JSONObject(body).getString("roomId")
}
}
tip

These examples use OkHttp for the network calls. The SDK does not bring it into your app, so add it yourself: implementation "com.squareup.okhttp3:okhttp:4.12.0".

Initialization of Live Stream​

  1. To initialize the live stream, first we have to initialize the VideoSDK. We can initialize the VideoSDK using initialize() method provided by the SDK. Call it once, for example in Application.onCreate(). Later calls do nothing.
initialize
fun initialize(context: Context)
  1. Now, we can create the live stream room using a factory method provided by the SDK called createRoom().

createRoom() creates the Room with the provided configuration, which includes the roomId, token, participantName, participantId and many more. It throws IllegalStateException if VideoSDK.initialize() has not run yet.

Only roomId and token are required. The other parameters have default values, so pass the ones you need by name.

Let's take a deeper look at the available configuration options first.

createRoom
fun createRoom(
roomId: String, // id of the live stream
token: String, // token used for authentication
participantName: String? = null, // name of participant
micEnabled: Boolean = true, // flag to enable-mic
camEnabled: Boolean = true, // flag to enable-camera
participantId: String? = null, // id of participant
mode: Mode? = null, // mode of participant
multiStream: Boolean? = null, // multiStream
customCameraTrack: CustomStreamTrack? = null,
customMicrophoneTrack: CustomStreamTrack? = null,
metaData: JSONObject? = null, // metaData
signalingBaseUrl: String? = null, // signalingBaseUrl
preferredProtocol: PreferredProtocol? = null, // preferredProtocol
codecSwitchEnabled: Boolean = true,
enableBatching: Boolean = true,
translationLanguage: String? = null,
speakingLanguage: String? = null,
maxResolution: MaxResolution? = null,
defaultCamera: FacingMode = FacingMode.front,
autoConsume: Boolean = true,
dynaCast: Boolean = false,
): Room
  • roomId :

    • This is a unique identifier that allows participants to join a specific live stream. Pass your streamId here.
    • It will be in the format of xxx-yyy-zzz and will be generated using the VideoSDK's Room API.
    • An empty roomId throws VideoSDKException with code 3073 (ERROR_INVALID_PARAMETER).
  • token :

    • The token you generated above.
    • An empty token throws VideoSDKException with code 3073 (ERROR_INVALID_PARAMETER). Other token problems are reported by the server when you call join().
  • mode :

    • This parameter defines the mode the participant will enter the live stream with.
    • Mode.SEND_AND_RECV: For hosts/co-hosts who can send and receive media.
    • Mode.RECV_ONLY: For audience members who can only receive media.
    • If you pass null, the participant joins in Mode.SEND_AND_RECV.
  • participantName:

    • This represents the name of the participant in the live streams.
    • It will accept String type value.
    • If you pass null or an empty name, the participant joins with a random 6-character name.
  • micEnabled:

    • This is a Boolean flag, indicating whether a participant's microphone will be automatically enabled when they join the live stream. It defaults to true.
    • Audience members don't publish audio, so it has no effect when they join. It still decides whether their microphone turns on by itself if they are later moved to Mode.SEND_AND_RECV with changeMode().
  • camEnabled:

    • This is a Boolean flag, indicating whether a participant's camera will be automatically enabled when they join the live stream. It defaults to true.
    • Audience members don't publish video, so it has no effect when they join. It still decides whether their camera turns on by itself if they are later moved to Mode.SEND_AND_RECV with changeMode().
  • metaData:

    • If you want to provide additional details about the participants joining the live stream, such as their profile image, you can pass that information in this parameter.
    • It has to be of JSONObject type.
    • This is an OPTIONAL parameter.
  • participantId:

    • This is a unique identifier for the participant inside the live stream.

      • Use it to link the participant to a user in your own database.
      • It has to be of String type.
      • This is an OPTIONAL parameter. By default, VideoSDK generates a unique id for each participant.
  • multiStream:

    • A Boolean flag, indicating whether the host's camera stream should send multiple resolution layers or a single resolution layer. If you pass null, it is true.
  • maxResolution:

    • The size the default camera opens at: MaxResolution.hd (1280x720) or MaxResolution.sd (960x540). If you pass null, it is MaxResolution.hd.
  • defaultCamera:

    • The camera the default camera track opens on: FacingMode.front or FacingMode.back. Default is FacingMode.front.
  • autoConsume:

    • If false, a participant's mic and camera are not received until you call consumeMicStreams() or consumeWebcamStreams() on that Participant from a coroutine. This saves bandwidth when there are many hosts. The consume methods take effect only when the room was created with autoConsume set to false. Default is true.
  • dynaCast:

    • If true, the server lowers the quality of the camera stream a host sends while no one is watching its larger layers, which saves upload bandwidth. It only works when the camera sends multiple layers: multiStream on and the VP8 codec. Default is false.
  • translationLanguage and speakingLanguage:

    • The language this participant receives live translations in, and the language they speak. If you pass null for translationLanguage, translation is off.

To learn about the other parameters, see Initialize Room.

caution

Make sure each participantId is used only once in a livestream. If a second participant joins with the same participantId, VideoSDK removes the participant who joined first.

With all the configuration options explained, here is how you can initialize the live stream.

class LiveStreamActivity : AppCompatActivity() {

private var liveStream: Room? = null

suspend fun getToken(): String {
...
}

suspend fun getStreamId(token: String): String {
...
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

lifecycleScope.launch {
//We will fetch token and streamId and store it in local variables
val token = getToken()
val streamId = getStreamId(token)

try {
// initialize the VideoSDK
VideoSDK.initialize(applicationContext)

// create a new room instance
liveStream = VideoSDK.createRoom(
roomId = streamId,
token = token,
participantName = "NAME HERE",
micEnabled = true,
camEnabled = true,
mode = Mode.SEND_AND_RECV, // Mode.RECV_ONLY for audience members
multiStream = false,
)
} catch (e: VideoSDKException) {
// 3073: the token or the streamId is empty
Log.e("VideoSDK", "createRoom failed: ${e.code} ${e.name}")
}

Log.d("VideoSDK", "onCreate: $streamId")
}
}
}

API Reference​

The API references for all the methods utilised in this guide are provided below.

Got a Question? Ask us on discord