Search code examples
androidmicrophoneandroid-audiomanager

isMicrophoneMute() and setMicrophoneMute() make Android application crash


i'm trying to mute the microphone on an Android phone, using the AudioManager tools. So i want to know whether the microphone is muted or not, using the isMicrophoneMute() method, but it makes my app crash. Same for the setMicrophoneMute() method.

I've given the MODIFY_PHONE_STATES, MODIFY_PHONE_STATE, and MODIFY_AUDIO_SETTINGS permissions to my application.

Here is my code :

private static AudioManager mAudioManager;


public static boolean unmuteMicrophone(final Context c) {
    if (c == null) {
        Log.v(TAG, "switchMicrophone: Context is null");
        return false;
    }
    ContentResolver cr = c.getContentResolver();
    if (cr == null) {
        Log.d(TAG, "switchMicrophone: ContentResolver is null, " + c);
        return false;
    }
    try {
        Log.v(TAG, "Trying to unmute microphone");
        mAudioManager.setMicrophoneMute(false);
        Log.v(TAG, "Microphone unmuted");
    }
    catch (Exception e) {
        Log.e(TAG, "Microphone can't be unmuted. Error : " + e);
    }
    return !mAudioManager.isMicrophoneMute(); //return the state of the microphone

}

This doesn't crash with the try/catch block, but it still doesn't affect the microphone state when i use the unmuteMicrophone() method.


Solution

  • You need to initialize your mAudioManager, use

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