Muting streams in Android

久未见 提交于 2019-12-05 10:32:32

First, beware it's not recommended

For a better user experience, applications MUST unmute a muted stream in onPause() and mute it again in onResume() if appropriate.

But I assume you know what you're doing, so here we go.

Note this line from the docs on setStreamMute

The mute command is protected against client process death: if a process with an active mute request on a stream dies, this stream will be unmuted automatically.

I've checked on my device and indeed, when I just exit my activity, stream stays muted. But as soon as I kill the process, mute goes away. Take a look at activity lifecycle.

As your current approach will not work reliably, you could write a foreground service which will trigger the mute - start that service from your activity. Also you would likely need to setStreamSolo.

Two important things.

  1. Volume==0 and muted are NOT the same thing. I.e. stream can have volume==0 but be not muted. Though if stream is muted, volume will always be 0
  2. mute requests are cumulative. I.e. if you've set mute twice, you must unmute twice as well - your code doesn't handle that

As a side note, for such app you would probably want to use widget instead of activity.


Off topic. It seems surprisingly lot of people don't quite get how booleans work. And as I see code such as yours regulary, here is a bit streamlined rewrite.

@Override
public void onCreate(Bundle savedInstanceState) {
    // ... setup just like you did

    // boolean is just like any other type. You can assign not only
    // constants, but expressions too
    mute = (mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)==0);
    tb_mute.setChecked(mute);
}

public void onButtonClicked(View view){
    mute = !mute; // invert value
    mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, mute);
    tb_mute.setChecked(mute);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!