Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mute audio speaker in android

Tags:

android

Can anybody tell me how to mute audio speaker in android. I tried

mAudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);

and

mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC,true);

But it does not work.

like image 834
jainal Avatar asked Oct 25 '11 03:10

jainal


2 Answers

Basically you need to know which stream you plan on hijacking, from what I've heard AudioManager is buggy. If your idea is to close all the existing streams and play only your sound, you could trick the other apps making noise by doing this:

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

then remove it later by

AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
AudioManager.setMode(AudioManager.MODE_NORMAL );

OR , you could mute it by changing the volume:

AudioManager audioManager = 
    (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.adjustVolume(AudioManager.ADJUST_LOWER,
    AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
like image 103
Reno Avatar answered Sep 22 '22 16:09

Reno


From Lollipop setStreamSolo was deprecated. There was another method in between, but now on Oreo, the right way to do this seems to be:

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);  
}
like image 33
Nick Cardoso Avatar answered Sep 22 '22 16:09

Nick Cardoso