简体   繁体   中英

Mute sound in Android with a button

I'd like to mute an android device with a button, what are the basic ways of doing it? (Also I would like to mute it for only a user inputted period of time if possible.

MuteBtn.setOnClickListener(new View.OnClickListener() { 
@Override public void onClick(View view) { 
float seconds = Float.parseFloat(inputSeconds.getText().toString());
long milsec = (long) (seconds * 1000); ; } });

There are multiple volume types in android. If you want to completely mute the device you have to mute all of those types.

AudioManager am = (AudioManager) con.getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_SYSTEM, (int) volumeLevel, AudioManager.FLAG_SHOW_UI /*or 0 for not showing system notification*/)

This will set the system vollume type to the volumeLevel you want. Do the same for all other volume streams (music, notifications etc..).

If you want to set it back to normal after a few seconds just use a Handler

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        //do whatever you want here 
        //after the delay is over
    }
}, milliseconds);

The tricky part here is that each stream type has a different max value. So before setting it back to bormal you must do this

int maxVol = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);

to get the max value for a specific stream type. And then set that value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM