Home > front end >  How to set media player to alarm usage in kotlin?
How to set media player to alarm usage in kotlin?

Time:08-29

Can someone please show me how to set my media player to play with alarm volume. I want to set the media player to alarm usage. I've tried what others have said and no success. Can I get a modern example in kotlin please.

CodePudding user response:

The MediaPlayer has a method called setAudioAttributes. The AudioAttributes passed to this method control the audio stream that audio file will be played in.

In order to make the MediaPlayer play in the alarm stream, You have to set the usage of the AudioAttributes to USAGE_ALARM. There is a dedicated Builder class for creating AudioAttributes which is used in the code below. Besides that You also want to specify the contentType attribute - for the alarms the most suitable will most likely be CONTENT_TYPE_MUSIC. Here is the example, modern kotlin code:

mediaPlayer.apply {
    reset()
    setAudioAttributes( // Here is the important part
        AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_ALARM) // usage - alarm
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
    )
    setDataSource(
        context,
        alarmSoundUri
    )
    isLooping = true
    prepare()
    start()
}
  • Related