简体   繁体   English

在静音模式下在Android应用中手动将声音静音吗?

[英]Manually mute sound in Android app when in silent mode?

I have tried finding an answer to this, but my searches kept returning irrelevant results... 我试图找到答案,但是我的搜索结果始终不相关。
So the problem is - I am writing a game that plays sound effects (no music just yet), and I set the stream type to Music. 所以问题是-我正在编写一个播放声音效果(暂时还没有音乐)的游戏,并将流类型设置为“音乐”。 However, when I put my phone in silent mode (no vibration either, if that matters) the app still plays sounds. 但是,当我将手机置于静音模式(也没有振动,如果很重要)时,应用仍会播放声音。 I can turn off the sound in the app using the volume keys, but what I expected (and what my future users would probably expect too) was that the app won't make a sound when the phone is in silent mode. 我可以使用音量键关闭应用程序中的声音,但是我所期望的(以及未来的用户可能也会期望)是,当手机处于静音模式时,该应用程序不会发出声音。

At this point, I am not sure if this should be automatically managed by the OS, or if I am expected to do something about it. 在这一点上,我不确定这是否应该由操作系统自动管理,或者是否应该对此做些什么。 I can surely detect the silent mode, set the volume to 0 in eg onResume , but that will probably overwrite the setting the users set up by pressing the volume buttons - so when they unmute the phone, the app either has to set the volume programmatically to a predefined value, or ideally, to a saved one from sharedPrefs... which sounds relatively cumbersome. 我肯定可以检测到静音模式,例如在onResume中将音量设置为0,但这可能会覆盖用户通过按音量按钮设置的设置-因此,当他们取消手机静音时,应用程序要么必须以编程方式设置音量到预定义的值,或者理想情况下是从sharedPrefs保存的值...听起来比较麻烦。 Is there a nicer solution? 有更好的解决方案吗?

This is how I initialize & then use sounds: 这是我初始化然后使用声音的方式:

soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new SparseIntArray();
soundPoolMap.put(CLICK_1, soundPool.load(activity, R.raw.click1, 1));
soundPoolMap.put(CLICK_2, soundPool.load(activity, R.raw.click2, 2));
...
float volume = 1.0f;
soundPool.play(soundPoolMap.get(soundID), volume, volume, 1, 0, 1f);

What I understand from your question is you want to mute your app when device is on silent mode . 我从您的问题中了解到的是,您希望在设备处于silent mode时将您的应用silent mode

Try to check the the RingerMode every time before your app play sound/music and play sound only when the ringer RingerMode is normal. 每次在您的应用播放声音/音乐之前尝试检查RingerMode并且仅在RingerMode正常时播放声音。

Here is the sample code. 这是示例代码。

AudioManager audio = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
switch (audio.getRingerMode())
{
    case AudioManager.RINGER_MODE_NORMAL:
    // Device is on Normal mode.
    // you can play music.
    break; 
    case AudioManager.RINGER_MODE_SILENT:
    // Device is on Silent mode.
    // you should not play sound now.
    break;
    case AudioManager.RINGER_MODE_VIBRATE:
    // Device is on Vibrate/Meeting mode.
    // you should not play sound but you can make vibrate device (if you want).
    break;
}

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

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