如何检查安卓麦克风是否可用?

rab*_*100 5 android

我目前正在编写一个使用麦克风来查询声级的应用程序。我正在使用 AlarmManager 每分钟查询声级。我面临的问题是我发现如果我使用另一个也使用麦克风的应用程序(例如分贝级阅读器),我的应用程序会因为麦克风不可用而崩溃。有没有办法检查麦克风当前是否正在使用?

Adh*_*ash 8

尝试捕获异常,因为当您尝试使用麦克风时遇到异常,您可以处理它。

“即使麦克风在使用中,麦克风实际上也会做好准备”

或者这个代码片段可能会给你一个想法

//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)

  • 我不认为放置“Exception”是一个好的做法。您可以使用“RuntimeException”,这是当音频源不可用时抛出的异常。可能很重要,但你却错过了。此外,“prepare()”会引发您可能会错过的其他异常,例如在 start() 之后和 setOutputFile() 之前调用,或者如果准备失败。至少就我而言,它总是可以准备,但如果源不可用,它就不会启动。因此,我捕获“RuntimeException”以查看它在“start()”上是否可用。其他异常不应该发生,我们应该手动修复它们(可能是错误的)。 (2认同)