0

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?

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
ammcom
  • 992
  • 1
  • 7
  • 24

1 Answers1

2

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

Community
  • 1
  • 1
Mikhail Naganov
  • 6,643
  • 1
  • 26
  • 26
  • 2
    it says: "As OpenSL ES is a native C API, non-Dalvik application threads which call OpenSL ES have no Dalvik-related overhead such as garbage collection pauses. However, there is no additional performance benefit to the use of OpenSL ES other than this. In particular, use of OpenSL ES does not result in lower audio latency, higher scheduling priority, etc. than what the platform generally provides." – ammcom Oct 30 '16 at 18:31
  • Java VM (in modern Android versions it's called ART) overhead can be significant. For achieving low latency, you may need your audio callback to be called reliably at 250 Hz frequency, thus your callback will only have less than 4ms time budget, so every microsecond counts, and you don't want these to be spent on JNI or GC. – Mikhail Naganov Oct 31 '16 at 00:06