8

So I'm trying to wrap my head around Audio Attributes. Here's what I have so far:

// alarm.getSound() will return a proper URI to pick a ringtone
Ringtone tone = RingtoneManager.getRingtone(this, alarm.getSound());
if (Build.VERSION.SDK_INT >= 21) {
    AudioAttributes aa = new AudioAttributes.Builder()
        .setFlags(AudioAttributes.USAGE_ALARM | AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .build();
    tone.setAudioAttributes(aa);
} else {
    tone.setStreamType(RingtoneManager.TYPE_ALARM);
}
tone.play();

This page talks about Audio Attributes and their "Compatibility Mappings." If I was previously using setStreamType(TYPE_ALARM) (like I am above) then it will set the CONTENT_TYPE_SONIFICATION and USAGE_ALARM flags. I want to get away from setStreamType so I was thinking that if I manually set those flags (like I am above) then when the ringtone plays it will use the Alarm volume. Well, it doesn't seem to work like that.

The above code still rings using my Nexus 6's Media volume instead of the Alarm volume. I'm on 6.0 with build MRA68N. What could I do different to use the Alarm volume?

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
  • Since it was not explicitly stated in either answer, those parameters as flags are ignored. It will always play at full volume through the default stream. Setting them in the appropriate `setter` **does** resolve it, though. – Abandoned Cart Jun 30 '18 at 21:15
  • This answer might help folks looking here: https://stackoverflow.com/a/53390067/826946 – Andy Weinstein Nov 20 '18 at 09:45

2 Answers2

9

Tested on Moto G Android 6.0

       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes aa = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
            ringtone.setAudioAttributes(aa);
        } else {
            ringtone.setStreamType(AudioManager.STREAM_ALARM);
        }
Nik Kober
  • 868
  • 11
  • 16
1

The response here helped but didn't work for me. I opened my own question here to resolve it.

Here is my working solution.

mediaPlayerScan = new MediaPlayer();
try {
  mediaPlayerScan.setDataSource(getContext(),
          Uri.parse(getString(R.string.res_path) + R.raw.scan_beep));

  if (Build.VERSION.SDK_INT >= 21) {
    mediaPlayerScan.setAudioAttributes(new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_ALARM)
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .build());
  } else {
    mediaPlayerScan.setAudioStreamType(AudioManager.STREAM_ALARM);
  }
  mediaPlayerScan.prepare();
} catch (IOException e) {
  e.printStackTrace();
}
nburn42
  • 697
  • 7
  • 25