I've been having an issue with using AudioRecord for Android. I've read as much as I can find online about it, but I cannot seem to get a good initialization. I have tried the Android 2.2 emulator, 1.5 emulator and my phone, an HTC Incredible running Froyo. The emulators and my phone fail initialization.
I've tried sampling rates of 8000, 11025, and 44100, formats of CHANNEL_IN_MONO/STEREO and CHANNEL_CONFIGURATION_MONO/STEREO, 8bit and 16bit encoding (8 bit makes the getMinBufferSize fail), and AudioSource of MIC and DEFAULT. All result in the variable test becoming 0 after running a get state(failed initialization).
It seems from everything I've read that this should correctly initialize the object. I have played around with the multiplier on buflen, to have it range from 512 (the result of the function) to 102400 because I had heard that HTC devices require something above 8192.
For testing my problem I made a new, small project that recreates my problem as simply as possible. I pull out the constants needed into local ints then run the constructor and access the getState method for checking if it worked.
package com.example.audiorecordtest;
import android.app.Activity;
import android.os.Bundle;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
public class audioRecordTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int freq =8000;
int chan = AudioFormat.CHANNEL_IN_MONO;
int enc = AudioFormat.ENCODING_PCM_16BIT;
int src = MediaRecorder.AudioSource.MIC;
int buflen = AudioRecord.getMinBufferSize(freq, chan, enc);
AudioRecord ar = new AudioRecord(src,freq,chan,enc,20*buflen);
int test = ar.getState();
}
}
--edit--
Please see Bill's answer.
--end edit--
Maybe you should check whether you acquired the correct permission. e.g. you need to get android.permission.VIBRATE in your AndroidManifest.xml file if you need to vibrate the device.
I think he means you need the RECORD_AUDIO permission in the manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
That worked for me.
来源:https://stackoverflow.com/questions/4161666/android-audiorecord-fails-to-initialize