playFile

fun AudioEngine.playFile(filePath: String, config: AudioStreamConfig = AudioStreamConfig()): AudioStream

Play an audio file through the engine.

Opens an AudioFileReader, creates an output AudioStream whose channel count matches the file, and decodes audio data in the stream callback. The stream is requested at the file sample rate; if the platform negotiates a different rate, frames are resampled. The reader is closed automatically when the stream transitions to StreamState.STOPPED or StreamState.CLOSED.

Playback ends naturally when the reader reaches the end of the file (the callback returns 0 frames). You can also stop playback early by calling AudioStream.stop or AudioStream.close.

Usage

val engine = AudioEngine.create()
val stream = engine.playFile("/path/to/music.mp3")
stream.start() // begins playback

// Later, to stop early:
stream.stop()
stream.close()

With coroutines

val stream = engine.playFile("/path/to/music.mp3")
stream.start()
stream.awaitState(StreamState.STOPPED) // suspends until playback ends
stream.close()

Return

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

Parameters

filePath

Absolute path to a local audio file, or an HTTP/HTTPS URL.

config

Base stream configuration. The AudioStreamConfig.sampleRate and AudioStreamConfig.channelCount properties will be overridden to match the file. The AudioStreamConfig.direction is forced to StreamDirection.OUTPUT. If the platform negotiates a different stream sample rate (JS AudioContext is often 48 kHz), file frames are resampled to that rate.

See also

Throws

if the file cannot be opened or decoded.