The accepted answer works fine in muting the system, but if you need to restore the state (e.g. when users pause / quit your app), please note that the semantics of the adjustStreamVolume
and setStreamMute
methods are different:
For setStreamMute
, from the documentation:
The mute requests for a given stream are
cumulative: the AudioManager can receive several mute requests from
one or more clients and the stream will be unmuted only when the same
number of unmute requests are received.
This does not seem to be the case for adjustStreamVolume
with AudioManager.ADJUST_MUTE
. In other words, if the status of the stream is already muted before you mute it with setStreamMute (stream, true)
, an immediate setStreamMute (stream, false)
will leave it in muted state, while adjustStreamVolume
with AudioManager.ADJUST_UNMUTE
may unmute the stream.
Depending on the use case, to emulate the old semantics, one way is to check the mute state before muting, something like the following -
To mute:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!audioManager.isStreamMute(stream)) {
savedStreamMuted = true;
audioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
}
} else {
audioManager.setStreamMute(stream, true);
}
To unmute:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (savedStreamMuted) {
audioManager.adjustStreamVolume(stream, AudioManager.ADJUST_UNMUTE, 0);
savedStreamMuted = false;
}
} else {
// Note that this must be the same instance of audioManager that mutes
// http://stackoverflow.com/questions/7908962/setstreammute-never-unmutes?rq=1
audioManager.setStreamMute(stream, false);
}
This assumes users are unlikely to invoke another app to mute the stream in-between and expect the stream to stay muted after your app unmutes (anyway there seems no way to check this).
Incidentally, the isStreamMute
method was previously hidden, and was only unhidden in API 23, enabling its use for this purpose.