如何在Android中静音音频扬声器

时间:2011-10-25 03:56:11

标签: android

有人能告诉我如何在Android中静音音频扬声器。 我试过了

mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);

mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC,true);

但它不起作用。

3 个答案:

答案 0 :(得分:8)

基本上你需要知道你计划劫持的流,我听说AudioManager是错误的。如果你的想法是关闭所有现有的流并只播放你的声音,你可以通过这样做来欺骗其他应用程序发出噪音:

AudioManager.setMode(AudioManager.MODE_IN_CALL);
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);

然后通过

删除它
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
AudioManager.setMode(AudioManager.MODE_NORMAL );

或者,您可以通过更改音量来静音:

AudioManager audioManager = 
    (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.adjustVolume(AudioManager.ADJUST_LOWER,
    AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

答案 1 :(得分:1)

来自Lollipop setStreamSolo已被弃用。中间有另一种方法,但现在在奥利奥,正确的方法似乎是:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    am.requestAudioFocus(new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE)
              .setAudioAttributes(new AudioAttributes.Builder().setUsage(USAGE_VOICE_COMMUNICATION).build()).build());
    am.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);  
}

答案 2 :(得分:1)

初始化:

var originalVolume = 0
private val audioManager: AudioManager by lazy {
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        return@lazy Util.appContext().getSystemService(AudioManager::class.java)
    } else {
        return@lazy Util.appContext().getSystemService(Context.AUDIO_SERVICE) as AudioManager
    }

}

需要静音的地方:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
   audioManager.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
} else {
   originalVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
   audioManager.mode = AudioManager.MODE_IN_CALL
   audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0)
}

需要取消静音的地方:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      audioManager.adjustVolume(AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_PLAY_SOUND);
} else {
      audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0)
      audioManager.mode = AudioManager.MODE_NORMAL
}