DEV Community

Moses Asiago
Moses Asiago

Posted on

Jetpack Compose Loading/How to load a YouTube video or YouTube Livestream channel to your Android application.

Jetpack Compose Loading/How to load a YouTube video or YouTube Livestream channel to your Android application
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

com.pierfrancescosoffritti.androidyoutubeplayer:core:12.1.0

open the file. I like separating my third-party dependencies from the default editor dependencies, so I will have the

// third-party dependencies
implementation("com.pierfrancescosoffritti.androidyoutubeplayer:core:12.1.0")
// end 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.

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
    })} 


Enter fullscreen mode Exit fullscreen mode

Then in your MainActivity load the LiveTvScreencomposable 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
        }
    }
} 


Enter fullscreen mode Exit fullscreen mode

That it, when you run the application, it should show as the first image shown in this article. Thank you.

Top comments (1)

Collapse
 
abdurahmon_4dd914494cf87c profile image
Abdurahmon • Edited

is this lib compatible with android tv focus management?