问题
I have a problem with below lines when using AudioFormat.ENCODING_PCM_8BIT
as AudioFormat. When using AudioFormat.ENCODING_PCM_16BIT
these work fine.
bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_8BIT);
audio = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_8BIT, bufferSize);
logcat:
03-26 10:03:49.643: E/AndroidRuntime(19949): FATAL EXCEPTION: main
03-26 10:03:49.643: E/AndroidRuntime(19949): java.lang.IllegalArgumentException: Invalid audio buffer size.
03-26 10:03:49.643: E/AndroidRuntime(19949): at android.media.AudioRecord.audioBuffSizeCheck(AudioRecord.java:340)
03-26 10:03:49.643: E/AndroidRuntime(19949): at android.media.AudioRecord.<init>(AudioRecord.java:237)
03-26 10:03:49.643: E/AndroidRuntime(19949): at com.kris.test.SoundMeter.runForCamMic(SoundMeter.java:57)
03-26 10:03:49.643: E/AndroidRuntime(19949): at com.kris.test.VolumeCalc.run(VolumeCalc.java:89)
03-26 10:03:49.643: E/AndroidRuntime(19949): at com.kris.test.StateChecker.micCalibration(StateChecker.java:159)
03-26 10:03:49.643: E/AndroidRuntime(19949): at com.kris.test.Settings$3.onClick(Settings.java:354)
03-26 10:03:49.643: E/AndroidRuntime(19949): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
03-26 10:03:49.643: E/AndroidRuntime(19949): at android.os.Handler.dispatchMessage(Handler.java:99)
03-26 10:03:49.643: E/AndroidRuntime(19949): at android.os.Looper.loop(Looper.java:137)
03-26 10:03:49.643: E/AndroidRuntime(19949): at android.app.ActivityThread.main(ActivityThread.java:4921)
03-26 10:03:49.643: E/AndroidRuntime(19949): at java.lang.reflect.Method.invokeNative(Native Method)
03-26 10:03:49.643: E/AndroidRuntime(19949): at java.lang.reflect.Method.invoke(Method.java:511)
03-26 10:03:49.643: E/AndroidRuntime(19949): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
03-26 10:03:49.643: E/AndroidRuntime(19949): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
03-26 10:03:49.643: E/AndroidRuntime(19949): at dalvik.system.NativeStart.main(Native Method)
回答1:
AudioRecord.getMinBufferSize
does not support PCM_8BIT
(see the AudioRecord source code), and will return ERROR_BAD_VALUE
(-2) if you pass a PCM_8BIT
format to it.
One solution would be to switch to using PCM_16BIT
encoding. Another possibility (which I haven't verified whether it works) is to ask for a minimum buffer size based on PCM_16BIT
and divide the returned size by 2 when constructing the AudioRecord
instance.
来源:https://stackoverflow.com/questions/15633452/audiorecord-invalid-audio-buffer-size