Android:startRecording()在SAMPLERATE设置为44100时调用未初始化的AudioRecord

时间:2015-02-16 10:50:41

标签: java android sampling audiorecord

当我为AudioRecord对象设置采样率为44100时,出现错误。当它是22050时它工作正常。

02-16 10:45:45.099 24021-24021 / com.vlad.jackcomms E / AudioRecord:frameCount 1024< minFrameCount 1792

02-16 10:45:45.099 24021-24021 / com.vlad.jackcomms E / AudioRecord-JNI:创建AudioRecord实例时出错:初始化检查失败。

02-16 10:45:45.099 24021-24021 / com.vlad.jackcomms E / android.media.AudioRecord:初始化本机AudioRecord对象时出现错误代码-20。

02-16 10:45:45.109 24021-24021 / com.vlad.jackcomms E / AndroidRuntime:FATAL

例外:主要     过程:com.vlad.jackcomms,PID:24021     java.lang.IllegalStateException:在未初始化的AudioRecord上调用startRecording()。

以下是相关代码:

private static final int RECORDER_SAMPLERATE = 22050*2;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
            RECORDER_SAMPLERATE, RECORDER_CHANNELS,
            RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

    recorder.startRecording();

2 个答案:

答案 0 :(得分:13)

您可以检查设备是否支持44100。 Android没有提供一个明确的方法来检查它,但有一个解决方案与AudioRecord类' getMinBufferSize函数。

public void getValidSampleRates() {
    for (int rate : new int[] {44100, 22050, 11025, 16000, 8000}) {  // add the rates you wish to check against
        int bufferSize = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_CONFIGURATION_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
        if (bufferSize > 0) {
            // buffer size is valid, Sample rate supported

        }
    }
}

答案 1 :(得分:9)

别忘了要求获得AUDIO_RECORD许可

private void checkRecordPermission() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},
                123);
    }