简体   繁体   中英

Exoplayer playWhenReady doesn't work Jetpack Compose

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM