Reputation: 1415
I'm developing a palyer app using jetpack compose
and I want to play/pause programatically.
here is my code:
val exoPlayer = ExoPlayer.Builder(context).build()
.also { exoPlayer ->
val mediaItem = MediaItem.Builder()
.setUri("www.mp4")
.build()
exoPlayer.setMediaItem(mediaItem)
exoPlayer.prepare()
exoPlayer.playWhenReady = true
}
DisposableEffect(
key1 = AndroidView(
factory = {
StyledPlayerView(context).apply {
hideController()
useController = false
player = exoPlayer
exoPlayer.videoScalingMode = C.VIDEO_SCALING_MODE_DEFAULT
exoPlayer.playWhenReady = true
}
}
),
effect = {
onDispose { exoPlayer.release() }
}
)
also I created a LaunchedEffect
which makes the player stop
after 5 seconds
here is my LaunchedEffect
:
LaunchedEffect(
key1 = shouldShowValidator,
block = {
if (shouldShowValidator) {
exoPlayer.playWhenReady = false
exoPlayer.pause()
}
}
)
I expect to pause
the player but i dont get that!
what is the problem ?
Upvotes: 0
Views: 656
Reputation: 1415
the problem is you should use Dispatchers.Main
for pausing the player
LaunchedEffect(
key1 = shouldShowValidator,
block = {
if (shouldShowValidator) {
withContext(
context = Dispatchers.Main,
block = {
exoPlayer.playWhenReady = false
exoPlayer.pause()
}
)
}
}
)
Upvotes: 1
Reputation: 422
I managed to pause the video after 5
seconds using the following code
val context = LocalContext.current
val exoPlayer = remember {
ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem.fromUri("<Enter video url>"))
prepare()
playWhenReady = true
}
}
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
delay(5000)
withContext(Dispatchers.Main) {
exoPlayer.playWhenReady = false
Toast.makeText(context, "Paused", Toast.LENGTH_SHORT).show()
}
}
}
DisposableEffect(
key1 = AndroidView(
factory = {
StyledPlayerView(context).apply {
player = exoPlayer
layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
}
}, modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(8.dp)
)
) {
onDispose {
exoPlayer.release()
}
}
PS: shouldShowValidator
could be the reason the video is not being paused in your case.
Upvotes: 1