Search code examples
androidandroid-mediaplayer

Android equivalent of setAudioAttributes() for MediaPlayer on API lower than 21


I'm setting the AudioAttribute for my MediaPlayer like this:

 mMediaPlayer.setAudioAttributes((AudioAttributes) new AudioAttributesCompat.Builder()
                    .setUsage(AudioAttributesCompat.USAGE_NOTIFICATION_RINGTONE).build().unwrap());

But apparently:

Call requires API level 21 (current min is 19): android.media.MediaPlayer#setAudioAttributes

So, how should set something like AudioAttribute to the MediaPlayer under API 21? I'm setting this attribute mainly to indicate my usage of the sound, which is Ringtone, is this property still needed under API 21?


Solution

  • I think you want setAudioStreamType(int), with the AudioManager.STREAM_NOTIFICATION type.

    However, you should consider using AndroidX's MediaPlayer2 instead of the native MediaPlayer. setAudioAttributes() is included, and you won't have to cast and unwrap to use it.

    To implement it:

    implementation 'androidx.media2:media2:1.0.0-alpha03'