I’m trying to fill a buffer with microphone input and analyze the contents. I create my buffers with:
int bufferSize=AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] buffer1 = new short[bufferSize];
Then in a separate class called Recorder, I have the following relevant code:
public short[] fillBuffer(short[] audioData, int bufferSize) {
AudioRecord recorder = new AudioRecord(AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize); // instantiate the
// AudioRecorder
if (recorder.getRecordingState() == android.media.AudioRecord.RECORDSTATE_STOPPED)
recorder.startRecording(); // check to see if the Recorder
// has stopped or is not
// recording, and make it
// record.
recorder.read(audioData, 0, bufferSize); // read the PCM
// audio data
// into the
// audioData
// array
if (recorder.getState() == android.media.AudioRecord.RECORDSTATE_RECORDING)
recorder.stop(); // stop the recorder
return audioData;
}
Then, when I call:
recorder.fillBuffer(buffer1, bufferSize);
and log the output, it always shows that the buffer is half full of what seems to be valid audio data, but half full of zeros.
Creating a buffer of half the normal size just threw an error, so I know it’s actually storing zeros. It isn’t just some weirdness with the buffer size. Am I doing something obviously wrong here? Keep in mind that this is my first Android application, though I’m pretty familiar with Java.
I actually think I may have solved this. I wrote this previously in C++ using Windows WaveIn and I used a short int array for the buffer, so I naturally tried to do that here. After reading the documentation again, though, it looks like I need a byte[] array. After changing it, it seems to work. Thanks for your help though, everyone!