Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we check the state of microphone of an android phone, if we can then how can I do this

I want to write a program to check if the internal microphone of android phone is on, off or in use by some other application.

If this is possible then how can I do this?

I read related questions at stack overflow but did not find a solution.

like image 486
blackfyre Avatar asked Oct 21 '25 00:10

blackfyre


1 Answers

Here's what I'm using to check if the microphone is busy (based on Odaym answer and my own tests):

(Updated with Android 6.0 Marshmallow compatibility, as suggested in comments)

  public static boolean checkIfMicrophoneIsBusy(Context ctx){
        AudioRecord audio = null;
        boolean ready = true;
        try{
            int baseSampleRate = 44100;
            int channel = AudioFormat.CHANNEL_IN_MONO;
            int format = AudioFormat.ENCODING_PCM_16BIT;
            int buffSize = AudioRecord.getMinBufferSize(baseSampleRate, channel, format );
            audio = new AudioRecord(MediaRecorder.AudioSource.MIC, baseSampleRate, channel, format, buffSize );
            audio.startRecording();
            short buffer[] = new short[buffSize];
            int audioStatus = audio.read(buffer, 0, buffSize);

            if(audioStatus == AudioRecord.ERROR_INVALID_OPERATION || audioStatus == AudioRecord.STATE_UNINITIALIZED /* For Android 6.0 */)
                ready = false;
        }
        catch(Exception e){
            ready = false;
        }
        finally {
            try{
                audio.release();
            }
            catch(Exception e){}
        }

        return ready;
    }
like image 65
bonnyz Avatar answered Oct 23 '25 14:10

bonnyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!