7

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.

jainal
  • 2,973
  • 2
  • 20
  • 18

3 Answers3

8

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);
Reno
  • 33,594
  • 11
  • 89
  • 102
2

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);  
}
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
2

init:

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
    }

}

where need to mute:

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

where need to unmute:

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
}
michael wang
  • 553
  • 3
  • 11