以 Media/Alarm/Ringtone 播放声音?

Playing sound as Media/Alarm/Ringtone?

我的应用程序发出警报。在 Android 声音设置中,此声音由 "Ring volume" 滑块而不是 "Alarm volume" 滑块控制。如何更改由 "Alarm volume" 控制的声音?

 public void doAlarm(){ 

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

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

我试过使用 setAudioAttributes,但结果是 "Media 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();
    }

我错过了什么?

我找到了解决方法:不使用 .create() 方法。而是使用 .setDataSource().prepare()。代码如下:

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();
}