1

I'm trying to create one screen with a video as a background using jetpack compose; I have found the next solution.

@Composable
fun VideoPlayer() {
    val context = LocalContext.current
    val exoPlayer = remember {
        SimpleExoPlayer.Builder(context)
            .build().apply {
                val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory(
                    context,
                    Util.getUserAgent(context, context.packageName)
                )
                val source = ProgressiveMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(
                        MediaItem.Builder().setUri(
                            Uri.parse("file:///android_asset/intro_video_android_19_9.mp4")
                        ).build()
                    )
                this.repeatMode = Player.REPEAT_MODE_ALL
                this.setMediaSource(source)
            }
    }

    AndroidView(
        factory = { localContext ->
            PlayerView(localContext).apply {
                player = exoPlayer
                player?.playWhenReady = true
                controllerHideOnTouch = true
                useController = false
                controllerAutoShow = false
                resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
                player?.play()
            }
        }
    )
}

The problem that faces this solution is that the playWhenReady doesn't work, so the screen keeps in black, and the only way to play the video is by interacting with the controllers.

My question is: do you know a way to force the autoplay of the video?

2 Answers2

1

use the player!!.prepare() before player!!.playWhenReady = true ,it's working for me

Swapnil
  • 121
  • 7
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Aug 30 '22 at 15:06
0

Well, I changed my approach of using ExoPlayer for this case, and instead, uses VideView that fit perfect for this use case, the final code is this:

@Composable
fun VideoPlayer() {
    AndroidView(
        factory = { localContext ->
            val uri =
                Uri.parse("android.resource://" + localContext.packageName + "/" + R.raw.intro_video_android_19_9)
            val videoView = VideoView(localContext)
            videoView.setVideoURI(uri)
            videoView.setOnCompletionListener {
                videoView.start()
            }
            videoView.start()
            videoView
        }
    )
}