Audio control - Android

In Android apps, 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:

AudioManager defines the following legacy channels:

// Set audio attributes
val player = MediaPlayer()
player.setAudioAttributes(
    AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY)
        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
        .setLegacyStreamType(AudioManager.STREAM_ACCESSIBILITY)
        .build()
)

// Provide media controls
button.setOnClickListener {
    if (player.isPlaying()) {
        player.pause()
    } else {
        player.start()
    }
}