我目前正在编写一个使用麦克风来查询声级的应用程序。我正在使用 AlarmManager 每分钟查询声级。我面临的问题是我发现如果我使用另一个也使用麦克风的应用程序(例如分贝级阅读器),我的应用程序会因为麦克风不可用而崩溃。有没有办法检查麦克风当前是否正在使用?
尝试捕获异常,因为当您尝试使用麦克风时遇到异常,您可以处理它。
“即使麦克风在使用中,麦克风实际上也会做好准备”
或者这个代码片段可能会给你一个想法
//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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12225 次 |
| 最近记录: |