Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a ringtone using the Alarm volume with setAudioAttributes?

Tags:

android

audio

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?

like image 488
Corey Ogburn Avatar asked Nov 27 '15 16:11

Corey Ogburn


2 Answers

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);
        }
like image 125
Nik Kober Avatar answered Nov 13 '22 08:11

Nik Kober


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();
}
like image 29
nburn42 Avatar answered Nov 13 '22 08:11

nburn42