asFlow

fun AudioFileReader.asFlow(chunkSize: Int = 4096, dispatcher: CoroutineDispatcher = defaultIoDispatcher): Flow<FloatArray>

Streams decoded audio data as a Flow of chunks.

Creates a cold Flow that reads audio frames from the reader in chunks of chunkSize frames and emits each chunk as a FloatArray. The flow runs on the specified dispatcher (defaulting to the platform IO dispatcher) and completes when AudioFileReader.isAtEnd is true or AudioFileReader.readFrames returns an empty array (end of file or a closed reader).

This is the recommended approach for processing large audio files without loading the entire file into memory.

Usage

val reader = AudioFileReader("/path/to/large-file.wav")

reader.asFlow(chunkSize = 8192).collect { chunk ->
// Process each chunk of interleaved PCM samples
processAudio(chunk)
}

reader.close()

Cancellation

The flow is cooperative with structured concurrency. Cancelling the collecting coroutine stops reading at the next chunk boundary. The caller is still responsible for calling AudioFileReader.close to release native resources.

Return

A Flow of FloatArray chunks containing interleaved PCM samples.

Parameters

chunkSize

The number of frames to read per emission. Each emitted FloatArray contains up to chunkSize * info.channelCount samples. Defaults to 4096 frames.

dispatcher

Dispatcher for the blocking reads. Defaults to the platform IO dispatcher (kotlinx.coroutines.Dispatchers.IO except JS, which uses Dispatchers.Default).

See also