I have an app in which I use an AudioTrack
in streaming mode to play dynamically generated audio. The app doesn\'t have to respond instantaneously to inputs, s
API level 19 adds a method in AudioTrack
called getTimeStamp(). From the documentation:
Poll for a timestamp on demand.
If you need to track timestamps during initial warmup or after a routing or mode change, you should request a new timestamp periodically until the reported timestamps show that the frame position is advancing, or until it becomes clear that timestamps are unavailable for this route.
You specify an AudioTimestamp object as the function's parameter and it will fill in the most recently "presented" frame position along with its "estimated" timestamp in nanoseconds. The nanosecond value corresponds to the millisecond value returned by SystemClock.uptimeMillis().
You can then determine the latency by figuring out when you wrote that particular frame to AudioTrack
vs. when getTimestamp()
thinks it actually presented. I have found this method to be more accurate than the other methods mentioned above.
You have to be careful though. The documentation says getTimeStamp()
is not supported on all platforms or all routes. You can determine if the call was successful by checking the boolean
return value. I have found with the devices I have tested that the function returns false until audio begins presenting, and then subsequent calls return true. I have only tested with AudioTrack
in STREAM_MUSIC
mode. Your mileage may vary.