0

我的应用会发出警报。在 Android 声音设置中,此声音由“响铃音量”滑块而不是“闹钟音量”滑块控制。如何更改由“警报音量”控制的声音?

 public void doAlarm(){ 

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

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

我曾尝试使用 setAudioAttributes,但结果是“媒体音量”滑块控制了音量:

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

我错过了什么?

4

1 回答 1

2

我找到了解决方案:不使用该.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();
}
于 2018-06-24T10:18:16.310 回答