Audio control - Jetpack Compose

In Jetpack Compose, you should always be able to control audio. When using MediaPlayer, you should implement buttons to call the start, pause and stop methods.

It is a best practice to play audio through the correct channel. Android has introduced AudioAttributes as a replacement of the STREAM types defined in AudioManager.

AudioAttributes defines the following content types:

AudioAttributes defines the following usages:

// Set audio attributes
val player = remember {
    MediaPlayer().apply {
        setAudioAttributes(
            AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .setLegacyStreamType(AudioManager.STREAM_ACCESSIBILITY)
                .build()
        )
    }
}
// Provide media controls
Button(
    onClick = {
        if (player.isPlaying) {
            player.pause()
        } else {
            player.start()
        }
    }
) {
    // Button content...
}