Search code examples
javaandroidringtoneringtonemanager

Playing sound as Media/Alarm/Ringtone?


My app plays an alarm. In the Android Sound settings, this sound is controlled by the "Ring volume" slider and not the "Alarm volume" slider. How can I change the sound to be controlled by the "Alarm volume"?

 public void doAlarm(){ 

    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    r = RingtoneManager.getRingtone(getApplicationContext(), notification);

    if (!r.isPlaying())
        r.play();
     }

I have tried using setAudioAttributes, but the result was that the "Media Volume" slider controlled the volume:

public void doAlarm(){

    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
    mp.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build());
    mp.setLooping(true);
    mp.start();
    }

What am I missing?


Solution

  • I have found a solution: not using the .create() method. Instead use .setDataSource() and .prepare(). Code below:

    public void ringAlarm() {
    
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null) {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        }
    
        if (alarmUri == null) {
            Log.e("ringAlarm" , "alarmUri null. Unable to get default sound URI");
            return;
        }
    
        MediaPlayer mp = new MediaPlayer();
        // This is what sets the media type as alarm
        // Thus, the sound will be influenced by alarm volume
        mp.setAudioAttributes(new AudioAttributes.Builder()
                                 .setUsage(AudioAttributes.USAGE_ALARM).build());
    
        try {
            mp.setDataSource(getApplicationContext(), alarmUri);
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        // To continuously loop the alarm sound
        mp.setLooping(true);
        mp.start();
    }