Reputation: 81
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?
Upvotes: 1
Views: 2284
Reputation: 200
use the player!!.prepare() before player!!.playWhenReady = true ,it's working for me
Upvotes: 1
Reputation: 81
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
}
)
}
Upvotes: 0