Jetpack Compose Loading/How to load a YouTube video or YouTube Livestream channel to your Android application.
Moses Asiago
Posted on November 27, 2023
I recently got an Android job to develop a Local Church TV android application. My choice was to go with the latest tech stack on the Android application. One of the features they wanted be implemented was the YouTube live stream to be loaded into the app. I had to research the best way to implement it, and the library: implementation("com.pierfrancescosoffritti.androidyoutubeplayer:core:12.1.0")
became handy in this. I will outline the steps you may follow to have your YouTube or video loaded into the Jetpack Compose Android application.
STEP 1
On your Android studio, left-hand side of the editor, open the project explorer
, expand the Gradle folder to get to the build.gradle--Module:app
as in the image below
open the file. I like separating my third-party dependencies from the default editor dependencies, so I will have the
// third-party dependencies
loaded to the build.gradle file. Sync the project and test running the application on your device to confirm the import didn't break the application.
implementation("com.pierfrancescosoffritti.androidyoutubeplayer:core:12.1.0")
// end third-party dependencies
STEP 2
Create a composable, for this case, I have called it LiveTvScreen
@Composable
fun LiveTvScreen(
videoId: String
) {
val ctx = LocalContext.current
AndroidView(factory = {
var view = YouTubePlayerView(it)
val fragment = view.addYouTubePlayerListener(
object : AbstractYouTubePlayerListener() {
override fun onReady(youTubePlayer:
YouTubePlayer) {
super.onReady(youTubePlayer)
youTubePlayer.loadVideo(videoId, 0f)
}
}
)
view
})}
Then in your MainActivity
load the LiveTvScreen
composable as below.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LiveTvScreen("BJ3Yv572V1A")
//'BJ3Yv572V1A' is the channel ID from
https://youtu.be/BJ3Yv572V1A
}
}
}
That it, when you run the application, it should show as the first image shown in this article. Thank you.
Posted on November 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.