Search code examples
androidmute

How to realize the mute function in android?


I want to realize the mute effect under the condition of mobile phone without root.

private AudioManager myAudioManager = null;

        myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

        int ringerMode  = myAudioManager.getRingerMode();       
        myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

        myAudioManager.setRingerMode(ringerMode); 

I test the above method. It has the effect on some mobile. And other mobile has no effect. Why?

What other way to mute except this?


Solution

  • There may be version sdk issue. By the way there are several streams in Android, which one do you want to mute? Try this code:

        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0); // mute music stream
        audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0); // mute ring stream
        if (Build.VERSION.SDK_INT >= 8) {
            audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
            audioManager.requestAudioFocus(null, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN);
        }