在 Android 上以静音模式播放声音的问题 [英] Troubles play sound in silent mode on Android

查看:55
本文介绍了在 Android 上以静音模式播放声音的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 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.

我发现了这个问题并使用了答案中的代码覆盖当前的音量状态.我的代码如下所示:

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

因为我的手机在静音模式下似乎返回 4,而在最大音量时返回 7.我不知道这是不是,它应该返回什么.我只是假设如果手机处于静音模式,它会返回 0.

since my phone seems to return 4 when it is in silent mode and 7 when it is at max volume. 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.

谁能指出我正确的方向?

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

这篇关于在 Android 上以静音模式播放声音的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆