以媒体/警报/铃声播放声音吗?

时间:2018-06-23 15:40:22

标签: java android ringtone ringtonemanager

我的应用发出警报。在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();
    }

我想念什么?

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案:不使用.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();
}