Android AudioRecord and AudioTrack codec options?

Donal Rafferty picture Donal Rafferty · Feb 3, 2010 · Viewed 8.5k times · Source

I currently use the AudioTrack and AudioRecord classes in Android.

I use the pure PCM data but I was wondering what my options are for other codecs?

From this page it seems I can only encode and decode using AMR narrowband?

I currently set up the Audio classes as follows:

arec = new AudioRecord(MediaRecorder.AudioSource.MIC,
                     11025,
                     AudioFormat.CHANNEL_CONFIGURATION_MONO,
                     AudioFormat.ENCODING_PCM_16BIT,
                     buffersize);

atrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
                     11025,
                     AudioFormat.CHANNEL_CONFIGURATION_MONO,
                     AudioFormat.ENCODING_PCM_16BIT,
                     buffersize,
                     AudioTrack.MODE_STREAM);

So my question is how do I change the encoding from PCM to one of the other supported codecs?

When I try to change ENCODING_PCM_16BIT on AudioFormat I only get the options of default or invalid encoding along with the PCM options.

Any links to tutorials on encoding and decoding audio on Android would be great if anyone knows of any or any help here greatly appreciated.

Thanks

EDIT: I have changed my code to the following:

arec = new AudioRecord(MediaRecorder.AudioSource.MIC,
                     11025,
                     AudioFormat.CHANNEL_CONFIGURATION_MONO,
                     **MediaRecorder.AudioEncoder.AMR_NB**,
                     buffersize);

atrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
                     11025,
                     AudioFormat.CHANNEL_CONFIGURATION_MONO,
                     **MediaRecorder.AudioEncoder.AMR_NB**,
                     buffersize,
                     AudioTrack.MODE_STREAM);

The code runs properly but I'm wondering does it actually encode the Audio as AMR_NB and if this is not a proper way to do it?

I was getting a buffer overflow when using raw PCM but none have appeared since using the new code with the MediaRecorder.AudioEncoder.AMR_NB used instead of the AudioFormat.PCM

Answer

CommonsWare picture CommonsWare · Feb 3, 2010

As the documentation states for AudioRecord and AudioTrack:

audioFormat     the format in which the audio data is represented. See ENCODING_PCM_16BIT and ENCODING_PCM_8BIT

you can only work with 8-bit and 16-bit PCM. If you want audio in other formats, either don't use AudioRecord and AudioTrack (try MediaRecorder and MediaPlayer) or you will have to transcode it using your own code, possibly leveraging the NDK.

AudioRecord and AudioTrack are designed specifically for cases where the audio in question is not supported by the OpenCORE multimedia engine, either because it's not a supported codec or not a supported streaming protocol (e.g., SIP).