ammcom ammcom - 1 month ago 13
Android Question

Android AudioTrack latency with playback

I am trying to play raw sound data using

AudioTrack
class in Android, I am using the
write
method, but I noticed that there is a latency between the write method returns and the actual sound is played, to make it simple let us use
AudioRecord
class as the following psedu code:

//init AudioTrack
//init AudioRecord
while(true){
byte [] buffer = new byte[1000];
int read = audioRecord(buffer,0,1000);
audioTrack.write(buffer,0,read);
}


I expect to get latency that is
read / sample rate
seconds but the actual sound is played after and extra of about 0.5 seconds, I really need the audio to be played with minimum latency, so does anyone has an explanation of what is going on and is there any available solution or should I accept this as it is a hardware issue?

Answer

I'm assuming your goal is to come up with some interactive audio solution (that is, where sound is played in response to some user action), because in this scenario low latency really matters.

On Android, to achieve the lowest latency you need to use Open SL ES API which is available to native (C++) code via NDK. The only Java side mechanism that can achieve low latency is SoundPool class, but it has limitations in what kind of sounds you can play.

For more information, see the page on high-performance audio, and also check out this SO answer: Low-latency audio playback on Android