How to configure a different stream to Chromecast on Android
Some streaming setups require you to cast a different stream to a Chromecast Receiver device than the one playing on a Chromecast Receiver device. For example, if you're playing HLS + FairPlay DRM on your iOS application, you need to cast a different source with DASH + Widevine DRM to your Chromecast application, because Chromecast applications aren't able to support FairPlay.
You can achieve this use case with the ChromecastConnection API.
ChromecastConnection API
The ChromecastConnection API allows you to implement callbacks related to Chromecast playback.
To achieve the described use case you can use the onStart (i.e. the start of a Chromecast session) to set a new stream,
and onStop (i.e. the end of a Chromecast session) to (re)set your previous stream.
You may also be interested in onJoin (i.e. joining an existing Chromecast session with a new device) or
onLeave (i.e. leaving an existing Chromecast session on a device).
The snippet below has two sources:
senderSourceis intended for playback on your sender device (i.e. your Android app)chromecastSourceis intended for playback on your Chromecast application
The setConnectionCallback method on the
Chromecast instance is used to:
- Set the
chromecastSourcewhen Chromecast playback starts through theonStartcallback. - Revert to the
senderSourcewhen Chromecast playback stops through theonStopcallback.
val senderSource = SourceDescription.Builder(
TypedSource.Builder("https://cdn.theoplayer.com/video/elephants-dream/playlist.m3u8")
.type(SourceType.HLS)
.build()
).build()
val chromecastSource = SourceDescription.Builder(
TypedSource.Builder("https://cdn.theoplayer.com/video/big_buck_bunny/big_buck_bunny_metadata.m3u8")
.type(SourceType.HLS)
.build()
).build()
val player = theoPlayerView.player
val chromecast = theoPlayerView.cast.chromecast
player.source = senderSource
chromecast.setConnectionCallback(object : ChromecastConnectionCallback {
override fun onStart(sourceDescription: SourceDescription?): SourceDescription = chromecastSource
override fun onStop(sourceDescription: SourceDescription?): SourceDescription = senderSource
override fun onJoin(sourceDescription: SourceDescription?): SourceDescription? = sourceDescription
override fun onLeave(sourceDescription: SourceDescription?): SourceDescription? = sourceDescription
})
The onJoin and onLeave implementations in the above snippet adhere to the default behavior.