AudioStreamCallback
Callback interface for audio stream events.
Implement this interface to receive callbacks from an AudioStream. Pass your implementation to AudioEngine.openStream to enable callback-driven (push/pull) audio I/O.
Threading
Android, Apple, JVM, and native desktop: onAudioReady runs on a dedicated worker thread. The platform audio callback does not invoke onAudioReady; samples move through a lock-free FIFO. Native effect processing stays on the audio thread. The worker is not real-time, so allocations are safe, but slow work still adds latency or underruns.
JS: an AudioWorklet renders on the audio thread. onAudioReady runs on the browser main thread via the worklet port, not on the render quantum. Allocations are allowed; blocking the main thread still underruns the worklet FIFO.
The other callbacks (onStreamStateChanged, onStreamError, onStreamUnderrun) may be called on any thread and do not have real-time constraints, though they should still return promptly.
Example
val callback = object : AudioStreamCallback {
override fun onAudioReady(buffer: FloatArray, numFrames: Int): Int {
for (i in 0 until numFrames) {
buffer[i] = sin(phase) // generate a sine wave
phase += phaseIncrement
}
return numFrames
}
override fun onStreamError(stream: AudioStream, error: KlarinetException) {
// Handle error, e.g., attempt to reopen the stream
}
}See also
Inheritors
Functions
Called when the audio stream needs data (output) or has data available (input).
Called when an unrecoverable error occurs on the stream.
Called when the stream's lifecycle state changes.
Called when an audio underrun (output) or overrun (input) is detected.