Created
March 19, 2023 06:46
-
-
Save bagus2x/f47ed38b95e4e365091137f2155bda64 to your computer and use it in GitHub Desktop.
Observe exoplayer state / Player.Listener in jetpack compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExoPlayerState( | |
context: Context, | |
private val scope: CoroutineScope | |
) : ExoPlayer by ExoPlayer.Builder(context).build(), Player.Listener { | |
@get:JvmName("playing") | |
var isPlaying by mutableStateOf(false) | |
private set | |
var duration by mutableStateOf(0.seconds) | |
private set | |
var currentPosition by mutableStateOf(0.seconds) | |
private set | |
init { | |
addListener(this) | |
} | |
override fun onIsPlayingChanged(isPlaying: Boolean) { | |
super.onIsPlayingChanged(isPlaying) | |
this.isPlaying = isPlaying | |
this.duration = getDuration().milliseconds | |
scope.launch { | |
while (true) { | |
[email protected] = getCurrentPosition().milliseconds | |
delay(200) | |
} | |
} | |
} | |
} | |
@Composable | |
fun rememberExoPlayerState( | |
lifecycleAware: Boolean = true | |
): ExoPlayerState { | |
val context = LocalContext.current | |
val scope = rememberCoroutineScope() | |
val exoPlayerState = remember { ExoPlayerState(context, scope) } | |
val lifecycleOwner = LocalLifecycleOwner.current | |
if (lifecycleAware) { | |
DisposableEffect(lifecycleOwner) { | |
val observer = LifecycleEventObserver { _, event -> | |
when (event) { | |
Lifecycle.Event.ON_RESUME -> exoPlayerState.play() | |
Lifecycle.Event.ON_PAUSE -> exoPlayerState.pause() | |
else -> {} | |
} | |
} | |
lifecycleOwner.lifecycle.addObserver(observer) | |
onDispose { | |
lifecycleOwner.lifecycle.removeObserver(observer) | |
exoPlayerState.release() | |
} | |
} | |
} | |
return exoPlayerState | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
full implementation: https://github.com/bagus2x/social-media-app/blob/26bac786d559b8a08249abd62b5ee183f8ff615a/android/app/src/main/java/bagus2x/sosmed/presentation/common/components/VideoPlayer.kt#L178