recordToFile

fun AudioEngine.recordToFile(filePath: String, format: AudioFileFormat = AudioFileFormat.WAV, config: AudioStreamConfig = AudioStreamConfig(direction = StreamDirection.INPUT)): AudioStream

Record audio from the microphone to a file.

Opens an AudioFileWriter and creates an input AudioStream that writes captured audio to the file in the stream callback. The writer is finalized and closed automatically when the stream transitions to StreamState.STOPPED or StreamState.CLOSED, ensuring the output file is properly finalized (e.g., WAV headers are written).

Usage

val engine = AudioEngine.create()

// Record to a WAV file (default format)
val stream = engine.recordToFile("/path/to/recording.wav")
stream.start() // begins recording

// ... record for a while ...

stream.stop() // stops recording and finalizes the file
stream.close()

Recording to a compressed format

val stream = engine.recordToFile(
filePath = "/path/to/recording.m4a",
format = AudioFileFormat.M4A,
config = AudioStreamConfig(sampleRate = 44100, channelCount = 1),
)
stream.start()

Return

An AudioStream in the StreamState.OPEN state. Call AudioStream.start to begin recording. The underlying AudioFileWriter is closed automatically when the stream is stopped or closed.

Parameters

filePath

Absolute path for the output file. Parent directories must already exist.

format

Audio file format to use for encoding. Defaults to AudioFileFormat.WAV.

config

Stream configuration. The AudioStreamConfig.direction is forced to StreamDirection.INPUT. The AudioStreamConfig.sampleRate and AudioStreamConfig.channelCount from this config are used for both the stream and the output file.

See also

Throws

if the output file cannot be created.

if format is not supported on the current platform.