Google Android Development Agency SASS

Monday 23 November 2009

Low latency audio playback in Android

One of the things which bugged me immensely about Android was it's lack of low-latency audio playback and a low-level audio API.

Unlike the iPhone, Android developers were stuck with high-level media player objects which basically only allowed you to chuck an MP3/OGG/Wav their way and hope for the best.

Well not any more my robot loving amigos!

After pulling my hair out trying different designs and playback algorithms working on the sequencing function of Tub Thumper Pro for Android, I finally found what I'd been looking for; an object for working with sample-level data, just like we've been doing on the iPhone.

android.Media.AudioTrack

I mean, it's not perfect, but here's what we're doing to run samples directly to the hardware without all of that mediaplayer-esque overhead (I've edited it to make it make sense outside of our app, but the theory is there):


//--load the sound file from the resource identifier into a byte array (c is Context)
InputStream s = c.getResources().openRawResource(resourceFile);
soundData = new byte[s.available()];
s.read(soundData);

//--setup an AudioTrack object, this one is running at 44.1Khz which worked best for us.
AudioTrack oTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT, intSize,AudioTrack.MODE_STREAM);

//--turn the audiotrack on
oTrack.play();
//--write something to the audio track, in this case the entire buffer
int playVal = oTrack.write(soundData,0,soundData.length);
//--we're turning it off here
oTrack.stop();

1 comment:

  1. Hi, what sort of latency are you getting? What Android devices have you tried it on?

    ReplyDelete