synced-audio
Play audio on Android at the exact time it's due. Glassworks plays Sendspin through it, in plain Kotlin.
A player for audio that has to be heard at a given time: several speakers playing one stream, or
sound kept in step with a picture. You push 16-bit PCM with the time each chunk is due on the
source's clock, and it plays each sample through an AudioTrack when that time comes. It watches
where the output really is (AudioTrack.getTimestamp) and corrects as it goes: a frame repeated or
dropped now and then for a small error, a jump for a large one.
It came out of the Glassworks sendspin player, where it keeps a panel in
sync with Music Assistant's other speakers. Package dev.glassworks.syncedaudio, MIT licensed, minSdk 23.
Use it in your own app
The scheduler needs to know when a stream time is heard on this device. Give it a StreamClock, or
use StreamClock.LOCAL when your source already times each chunk on System.nanoTime():
val sink = AudioTrackSink()
val scheduler = PlaybackScheduler(sink, { StreamClock.LOCAL })
thread(name = "audio", isDaemon = true) {
try {
while (playing) if (!scheduler.step()) scheduler.awaitWork(200)
} finally {
scheduler.end()
sink.close() // the audio thread owns the output: it releases the AudioTrack when it stops
}
}
scheduler.start(PcmFormat(sampleRate = 44_100, channels = 2))
// From your source's thread, as audio arrives: the chunk's first frame is heard at presentAtNanos.
scheduler.push(PcmChunk(presentAtNanos / 1000, pcm, frames, 44_100, 2))
clear() drops what's buffered (a seek), end() stops the stream, and AudioTrackSink.setGain
sets the volume from any thread. Set outputDelayUs when the speaker adds delay of its own, such as
a Bluetooth speaker or an amplifier.
A source on another device's clock implements StreamClock. localUs turns a stream time into
local microseconds, ready stays false until the clock is known, and rate gives the drift between
the two clocks if you track it.
What's in it
PlaybackScheduler |
The player: a jitter buffer ordered by stream time, and a 10 ms write loop that lines each sample up with the clock. stats() counts its corrections, the silence and the late audio. |
StreamClock, PcmFormat, PcmChunk |
The source's clock, the format and the audio. |
AudioSink, AudioTrackSink, PcmTrack, openAudioTrack |
The output: an AudioTrack (USAGE_MEDIA, a 100 ms streaming buffer), or your own. |
It needs no permissions. Logs use the tag Glassworks.SyncedAudio.
How it stays in sync
Before each 10 ms block, the scheduler compares two times: when the next buffered frame is due, and when the next frame it writes will come out of the speaker. The second comes from the output's timestamps, smoothed. The difference decides the block:
| Error | What the scheduler does |
|---|---|
| Early by a block or more | Writes silence: the start of a stream, or a gap between chunks. |
| Over 3 ms | Jumps once: writes that much silence, or drops that much audio. |
| Within 3 ms | Repeats or drops one frame in the block, once the smoothed error passes 150 µs. That's at most 0.21 % of speed at 48 kHz, too little to hear. |
Audio that arrives after it should have played is dropped.
Gradle
Not on Maven Central yet. In this repository: implementation(project(":synced-audio")). An Android
library (AAR), minSdk 23 (Android 6), with no dependencies beyond the Kotlin standard library.
Tests
./gradlew :synced-audio:testDebugUnitTest. PlaybackSchedulerTest plays against a simulated
output with a virtual clock: a DAC running fast or slow, output latency, and noisy timestamps. It
checks when every sample is really heard against when it was due. Ideal output stays within
0.1 ms, and a DAC off by 120 ppm stays within 0.5 ms. AudioTrackSinkTest covers the output's gain
and track handling.