简体   繁体   English

麻烦在Android上以静音模式播放声音

[英]Troubles play sound in silent mode on Android

I am writing an android application to simply play an alarm no mater what mode the phone even if it is in silent mode. 我正在编写一个Android应用程序来简单地播放一个警报,即使它处于静音模式,也不管电话是什么模式。

I found this question and used the code from the answer to override the current volume state. 我发现了这个问题并使用了答案中的代码来覆盖当前的卷状态。 My code looks like this: 我的代码看起来像这样:

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (alert == null){
        // alert is null, using backup
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alert == null){
            // alert backup is null, using 2nd backup
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    }
}
ringtone = RingtoneManager.getRingtone(getApplicationContext(), alert);

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
if(volume == 0){
    volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
}
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

if(ringtone != null){
    ringtone.play();
}

By debugging it seems that my problem start in this line: 通过调试,似乎我的问题从这一行开始:

int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);

since my phone seems to return 4 when it is in silent mode and 7 when it is at max volume. 因为我的手机在静音模式下似乎返回4,而在最大音量时则为7。 I do not know if this is, what it is supposed to return. 我不知道这是不是,应该归还什么。 I just supposed that if the phone is in silent mode it would return 0. 我只是假设如果手机处于静音模式,它将返回0。

Anyone who can point me in the right direction? 谁可以指出我正确的方向?

Answered the question myself, spend more time reading the documentation in-depth. 我自己回答了这个问题,花了更多的时间深入阅读文档。

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (alert == null){
        // alert is null, using backup
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alert == null){
            // alert backup is null, using 2nd backup
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    }
}
ringtone = RingtoneManager.getRingtone(getApplicationContext(), alert);

after setting the ringtone I had to set the stream type for the ringtone: 设置铃声后,我必须设置铃声的流类型:

    ringtone.setStreamType(AudioManager.STREAM_ALARM);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM