Android AudioRecord麻烦

时间:2015-01-10 16:33:04

标签: java android android-activity android-manifest


private static final int SampleRate = 8000; 
private static final int Channels = AudioFormat.CHANNEL_IN_MONO;
private static final int Encoding = AudioFormat.ENCODING_PCM_16BIT;

private void startRecording(){
    int bufferSize = AudioRecord.getMinBufferSize(SampleRate, Channels,  AudioFormat.ENCODING_PCM_16BIT);
       if (bufferSize > 0) {
            recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SampleRate, Channels, Encoding, BufferElements2Rec*BytesPerElement);
            recorder.startRecording();
            isRecording = true;
            recordingThread = new Thread(new Runnable(){
                public void run(){
                    writeAudioDataToFile();
                }
            },"AudioRecorder Thread");
            recordingThread.start();
       }
}

这适用于设备模拟器,我有任何问题,但在真正的手机不起作用。我收到了这个错误:

java.lang.IllegalStateException: startRecording() called on an unitialized AudioRecord.

我放入了我的清单:

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

2 个答案:

答案 0 :(得分:2)

正如AudioRecord构造函数的documentation所说,

  

你应该在施工后立即调用getState()进行确认   该对象可用。

可能的状态是:

<强> STATE_INITIALIZED

<强> STATE_UNINITIALIZED

在您的情况下,录像机未正确初始化,因此您在调用startRecording()时会收到IllegarArgumentException。

其中一个原因可能是你的SampleRate,即8000.根据文档,44100Hz是保证在所有设备上工作的唯一速率,所以请先尝试这个速率(同样,文档没有明确说明8000HZ作为有效率。)

然后,在您的代码中,将SampleRate更改为44100并检查对象状态,例如:

private static final int SampleRate = 44100;

以后:

recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SampleRate, Channels, Encoding, BufferElements2Rec*BytesPerElement);

if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
    recorder.startRecording();
    isRecording = true;
    //rest of the code
}
else {
    //not initialized properly
}

答案 1 :(得分:1)

在某些情况下(我在Android 6上遇到同样的问题而不是在5上)当你第一次启动应用时你需要转到设置&gt;应用&gt; Yourapp&gt;权限并让应用使用麦克风,我打开它后,错误消失了。

更好的做法是在启动时检查sdk号码,并在应用程序内向用户请求权限以防止错误(用您需要的权限替换PUT_YOUR_PERMISSION_HERE) -

//check for permission
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M  &&     checkSelfPermission(Manifest.permission.PUT_YOUR_PERMISSION_HERE)
                        != PackageManager.PERMISSION_GRANTED) {

                    requestPermissions(new String[]{Manifest.permission.PUT_YOUR_PERMISSION_HERE},
                            MY_PERMISSIONS_REQUEST_PUT_YOUR_PERMISSION_HERE);

                    // MY_PERMISSIONS_REQUEST_PUT_YOUR_PERMISSION_HERE is an
                    // app-defined int constant

                    return;
                }