jainal
jainal

Reputation: 3021

How to mute audio speaker in 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.

Upvotes: 8

Views: 10931

Answers (3)

michael wang
michael wang

Reputation: 551

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
}

Upvotes: 2

Nick Cardoso
Nick Cardoso

Reputation: 21733

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

Upvotes: 2

Reno
Reno

Reputation: 33782

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

Upvotes: 8

Related Questions