Home > Mobile >  How to manage MediaPlayer Properly in jetpack compose?
How to manage MediaPlayer Properly in jetpack compose?

Time:11-24

Whenever i want to navigate to other screen i want my MediaPlayer should Stop where is best place to using the stop() function .

@Composable
 fun MenuScreen(navController: NavController) {

val context = LocalContext.current
val menuMusic : MediaPlayer = MediaPlayer.create(context , R.raw.menu_music)
menuMusic.isLooping = true
menuMusic.start()

Box(
    modifier = Modifier
        .fillMaxSize()
        .background(color = darkBackground)
) {...}

CodePudding user response:

If you want your MediaPlayer to start when your composable enters the composition and stop when it leaves the composition, you would do this:

val context = LocalContext.current
val menuMusic: MediaPlayer = MediaPlayer.create(context , R.raw.menu_music)

DisposableEffect(Unit) {
    menuMusic.isLooping = true
    menuMusic.start()

    onDispose {
        menuMusic.stop()
    }
}
  • Related