Android: IllegalArgumentException: Invalid audio buffer size

I was making an app which was streaming audio from the microphone, but for some odd reason it was throwing exceptions.

Here's the initialisation code.

int RECORDER_SAMPLERATE = 8000;
int RECORDER_CHANNELS = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_8BIT;

 

int bufferSizeInBytes = AudioTrack.getMinBufferSize(
    RECORDER_SAMPLERATE,
    RECORDER_CHANNELS,
    RECORDER_AUDIO_ENCODING
);

 

AudioTrack audioTrack = new AudioTrack(
    AudioManager.STREAM_MUSIC,
    RECORDER_SAMPLERATE,
    RECORDER_CHANNELS,
    RECORDER_AUDIO_ENCODING,
    bufferSizeInBytes,
    AudioTrack.MODE_STREAM);

Now it looked completely fine to me, and it took a good while for me to figure out because I never expected AudioTrack.getMinBufferSize() to actually return an error!

The reason was that AudioTrack could not be initialised for the given PCM encoding. I was trying to reduce bandwidth by making it 8bit, but the recording had to be in 16bit PCM.

It's not an obvious one, but it's a bug I could only catch find after testing on multiple devices.

rcTsgPpveU6jbkYyuKpO7w2
Bug caught.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog