Search code examples
androidandroid-asynctaskpcmaudiorecord

PCM stream/Microphone stutter


I am currently developing an Android application that has to record the microphone input as PCM stream.

Whenever I record something, I experience some strange stutter and I can't find a solution to this.

Here's my code:

In my MainActivity I have an ASyncTask for the Microphone input:

ArrayList<byte[]> mBufferList;

@Override
protected String doInBackground(String... params) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    mMicrophone = new Microphone();
    mMicrophone.init();
    byte[] buffer;
    while (mRecord) {
  try {
        mMicrophone.record();
        buffer = mMicrophone.getBuffer();
        mBufferList.add(buffer);            
      }
      catch
      {
      }
    }
}

In my Microphone class I initialize the AudioRecorder:

    public void init() {
    Log.d("DEBUG", "Microphone: Recording started");
    mBufferSize = AudioRecord.getMinBufferSize(44100,
            AudioFormat.CHANNEL_IN_STEREO,
            AudioFormat.ENCODING_PCM_16BIT);
    mRecorder = new AudioRecord(AudioSource.MIC, 44100,
            AudioFormat.CHANNEL_CONFIGURATION_MONO,
            AudioFormat.ENCODING_PCM_16BIT, mBufferSize);
    mRecorder.startRecording();
    mBuffer = new short[mBufferSize];
}

The record method:

public void record() throws IOException {
    mRecorder.read(mBuffer, 0, mBufferSize);
}

Short[] to Byte[]:

public byte[] shortToBytes(short[] sData) {
    int shortArrsize = sData.length;
    byte[] bytes = new byte[shortArrsize * 2];

    for (int i = 0; i < shortArrsize; i++) {
        bytes[i * 2] = (byte) (sData[i] & 0x00FF);
        bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
        sData[i] = 0;
    }
    return bytes;
}

Method to retrieve the buffer:

public byte[] getBuffer() {
    byte[] buffer = shortToBytes(mBuffer);
    return buffer;
}

I have uploaded a wav-file which demonstrates the stutter effect. I'm saying 'One': Wav-File

I already tried to change the samplerates, buffersizes et cetera, but with no avail.

Any help is very appreciated! Would be great if anyone could help me out!

Please note: This error is not caused by the way I replay the pcm stream since I have tested it on an android devices and even sent the raw data to a server to convert the file to a wav there.


Solution

  • After hours and hours of desperately searching for a solution I have finally found the error.

    I accidentaly created my short buffer in the Microphone class like this:

    mBuffer = new short[mBufferSize];
    

    The buffer size is in bytes though, so I of course have to use mBuffersize/2

    mBuffer = new short[mBufferSize/2];
    

    I will keep my question online in case anyone is interested in the code and /or has a similar problem.