How To Check If Android Microphone Is Available For Use?
Solution 1:
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;
}
Solution 2:
if you use AudioRecord
then call startRecording()
and after that you should check recorder's state: getRecordingState()
. If recording was started successfully (it means mic is available), it will return 3 (AudioRecord.RECORDSTATE_RECORDING
) otherwise it will return 1 (AudioRecord.RECORDSTATE_STOPPED
)
Here's code for this function in Kotlin:
private fun isMicAvailable(audioRecord: AudioRecord): Boolean {
audioRecord.startRecording()
val isAvailable = audioRecord.recordingState == AudioRecord.RECORDSTATE_RECORDING
audioRecord.stop()
audioRecord.release()
return isAvailable
}
Solution 3:
I also want to detect whether microphone is being used or not. My solution is using AudioManager to get current mode.
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (am.getMode() == AudioManager.MODE_NORMAL){
//microphone is available.
}
Other modes usage like MODE_IN_COMMUNICATION, MODE_IN_CALL, please check https://developer.android.com/reference/android/media/AudioManager.html#MODE_NORMAL
Post a Comment for "How To Check If Android Microphone Is Available For Use?"