rabz100 rabz100 - 3 months ago 18
Android Question

How to check if android microphone is available for use?

I am currently programming an app that uses the microphone to query the sound level. I am using AlarmManager to query the sound level every minute. The problem I am facing is that I discovered if I am using another app that uses the microphone too (e.g. decibel level reader) my app will crash because the microphone is not available. Is there a way to check if the microphone is currently being used or not?

Answer

Try Catching exception, as you get exception when you try to use microphone you can handle it.

"The microphone will actually prepare fine even if the microphone is in use"

OR this code snippet may give you an idea

//returns whether the microphone is available
    public static boolean getMicrophoneAvailable(Context context) {
        MediaRecorder recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        recorder.setOutputFile(new File(context.getCacheDir(), "MediaUtil#micAvailTestFile").getAbsolutePath());
        boolean available = true;
        try { 
            recorder.prepare();
            recorder.start();

        }
        catch (Exception exception) {
            available = false;
        }
        recorder.release();
        return available;
    }