Files
rosetta/docs/guide/audio.md
T
2026-10-31 13:56:21 -05:00

255 lines
11 KiB
Markdown

# Audio
Every audio format opens as the same streaming **Decoder** and loads as the same **Audio** value. A Decoder hands
out interleaved 32-bit float samples a block at a time, for playback and long files. An Audio holds the whole sound
in one buffer, for editing with `F.ops.audio`. Encoders take either one. A FLAC, an MP3 and an Ogg Vorbis file are
used the same way.
```luau
local song = assert(F.audio.load(flacBytes)) -- Audio: the whole file decoded
print(song.sampleRate, song.channels, song.frames) -- 44100 2 44100
print(song.tags.title, song.tags.artist) -- Docs Tone formats-luau
local quieter = F.ops.audio.gainDb(song, -6)
local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192 })) -- a buffer
assert(F.detect(mp3) == "mp3")
```
## The types
### Audio
`F.audio.load(src)` and `F.load(src)` return an Audio. `F.Types.Audio.new(sampleRate, channels, frames)` makes a
silent one.
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"audio"` | |
| `sampleRate` | number | frames per second (Hz) |
| `channels` | number | samples per frame |
| `frames` | number | the length in sample frames (`frames / sampleRate` = seconds) |
| `samples` | buffer | interleaved f32, `frames * channels * 4` bytes |
| `tags` | `{ [string]: string }` | `title`, `artist`, `album`, `date`, `genre`, `track`, `comment`, ...; keys are lower case |
| `meta` | table | `meta.source = { format = "flac", ... }` after a load |
**Sample layout.** Samples are little-endian 32-bit floats, nominally in -1..1. The values are not clipped: the
encoders clip. Frame `i` (0-based), channel `c` (0-based) is at byte offset `(i * channels + c) * 4`:
```luau
local a = F.Types.Audio.new(8000, 2, 8000) -- 1 s of stereo silence at 8 kHz
for i = 0, a.frames - 1 do
local v = math.sin(2 * math.pi * 440 * i / a.sampleRate) * 0.5
buffer.writef32(a.samples, (i * 2 + 0) * 4, v) -- left
buffer.writef32(a.samples, (i * 2 + 1) * 4, -v) -- right
end
assert(buffer.len(a.samples) == a.frames * a.channels * 4)
local wav = assert(F.save(a, nil, { format = "wav" }))
```
**Channel order.** Channels come in WAVE order, whatever the source format uses: FL, FR, C, LFE, BL, BR, SL, SR.
Mono is one channel and stereo is FL, FR. Vorbis and Opus streams are reordered on decode.
### Decoder
`F.audio.open(src)` and `F.open(src)` return a Decoder.
| Member | Meaning |
|---|---|
| `sampleRate`, `channels` | as in Audio |
| `frames` | total frames (an estimate for VBR streams without an index; 0 = unknown) |
| `duration` | seconds |
| `bitrate` | average bits per second |
| `tags` | as in Audio |
| `dec:read(n, out?)` | `buffer, count`: up to `n` frames as interleaved f32, and how many were read (0 at the end). The returned buffer is `out` when `out` holds at least `n * channels * 4` bytes; otherwise it is a new buffer. Only the first `count * channels * 4` bytes are valid. |
| `dec:seek(seconds)` | moves the read position |
| `dec:position()` | the read position in seconds |
Some formats add their own fields. For example, `bitsPerSample` on WAV, FLAC and AIFF, and `pictures` (cover art)
on FLAC and M4A.
```luau
local dec = assert(F.audio.open(flacBytes))
assert(dec.sampleRate == 44100 and dec.channels == 2 and dec.duration == 1)
local block = buffer.create(1024 * dec.channels * 4) -- reused for every read
local total, peak = 0, 0
while true do
local out, n = dec:read(1024, block)
if n == 0 then break end
for k = 0, n * dec.channels - 1 do
peak = math.max(peak, math.abs(buffer.readf32(out, k * 4)))
end
total += n
end
assert(total == dec.frames)
dec:seek(0.5)
assert(math.abs(dec:position() - 0.5) < 0.001)
```
## Loading
| Call | Gives |
|---|---|
| `F.audio.load(src, opts?)` | an Audio: the whole file decoded |
| `F.audio.open(src, opts?)` | a Decoder |
| `F.load` / `F.open` | the same, when you don't know the category in advance |
| `F.ops.audio.toAudio(decoder)` | the rest of a Decoder as an Audio (`opts.maxFrames` limits it) |
`src` is a buffer, a string of bytes, or a path on hosts with files. The format is detected from the content (see
the guide's [README](README.md#inputs)). Options:
| Option | Formats | Meaning |
|---|---|---|
| `format` | all | decode as this format (`"mp3"`, `"wav"`, ...) and skip detection |
| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac | `Err.LIMIT` past this many frames |
| `stereo` | opus | downmix surround streams to stereo |
```luau
local tags = assert(F.audio.open(mp3Bytes)).tags -- opening reads the tags; nothing is decoded yet
assert(tags.title == "Docs Tone" and tags.album == "Guide" and tags.date == "2026")
local ogg = assert(F.audio.open(oggBytes))
print(ogg.bitrate, ogg.duration)
local bad, err = F.audio.load("not audio at all")
assert(bad == nil and err.code == F.Err.UNKNOWN_FORMAT)
```
## Editing: `F.ops.audio`
Every function returns a new Audio, or `nil, err` for bad arguments. Times are in seconds. Rates and channel counts
of other inputs are converted to the first input's.
| Function | Does |
|---|---|
| `toAudio(audioOrDecoder, opts?)` | an Audio as it is, or a Decoder read to its end |
| `gain(a, factor)`, `gainDb(a, dB)` | scale every sample |
| `normalize(a, target?)` | scale so the peak is `target` (default 1) |
| `peak(a)`, `rms(a)` | `level, { per channel }` |
| `fade(a, inSeconds?, outSeconds?)` | linear fade-in / fade-out |
| `trim(a, start, stop?)` | the seconds `[start, stop)` |
| `concat({ a, b, ... })` | one after the other |
| `mix({ a, b, ... }, weights?)` | the sum, as long as the longest |
| `remix(a, channels, m?)` | any channel count. `m[out][in]` is an explicit matrix; the default comes from `matrix(from, to)` |
| `downmix(a, channels?)` | fewer channels (default 2), with ITU-R BS.775 coefficients |
| `upmix(a, channels)` | more channels: mono to FL / FR, stereo to FL / FR, the others silent |
| `matrix(from, to)` | the default remix matrix |
| `resample(a, rate, opts?)` | a new rate, band-limited; `opts.quality = "low" \| "medium" \| "high"` |
```luau
local A = F.ops.audio
local a = assert(F.audio.load(wavBytes))
local mono = assert(A.downmix(a, 1))
local clip = assert(A.trim(A.resample(mono, 22050), 0.25, 0.75))
assert(clip.channels == 1 and clip.sampleRate == 22050 and clip.frames == 11025)
local loop = assert(A.concat({ clip, A.fade(clip, 0.05, 0.05) }))
local level, perChannel = A.peak(loop)
local loud = assert(A.normalize(loop, 0.9))
assert(math.abs(A.peak(loud) - 0.9) < 1e-4)
local both = assert(A.mix({ a, loud }, { 0.5, 0.5 })) -- loud is converted to a's 44.1 kHz stereo
assert(both.channels == 2 and both.sampleRate == 44100)
```
## Saving and converting
`F.save(value, dest?, opts?)` takes an Audio or a Decoder. It picks the format from `opts.format`, else from the
destination's extension, else from the source format (`meta.source.format`). A Decoder has no source format, so pass
one. A Decoder is encoded as it is read, without decoding the whole file first.
```luau
local a = assert(F.audio.load(wavBytes))
local flac = assert(F.save(a, nil, { format = "flac", level = 8 })) -- buffer
local again = assert(F.save(F.audio.load(flac))) -- the source format: flac
local opus = assert(F.save(F.audio.open(mp3Bytes), nil, { format = "opus", bitrate = 64000 })) -- streamed
assert(F.audio.open(opus).sampleRate == 48000)
local wav24 = assert(F.convert(flacBytes, "wav", { sampleFormat = "s24" })) -- load + save
assert(F.audio.open(wav24).bitsPerSample == 24)
```
<!-- doc:files -->
```luau
assert(F.save(F.audio.open("assets/tone.flac"), "out/tone.ogg", { quality = 5 })) -- file in, file out
assert(F.detect("out/tone.ogg") == "vorbis")
```
Encoder options:
| Format | Options |
|---|---|
| wav | `sampleFormat = "u8" \| "s16" \| "s24" \| "s32" \| "f32"` (default `"s16"`), `rf64`, `extensible`, `channelMask`, `tags` |
| flac | `level` 0..8 (default 5), `bits` 4..24 (default: the source depth, else 16), `blockSize`, `seekInterval`, `padding` |
| mp3 | `bitrate` **in kbps** (default 128), `layer` 3 or 2 (MP2), `mode = "stereo" \| "joint" \| "mono"`, `sampleRate`, `id3`, `resampleQuality` |
| vorbis | `quality` -1..10 (default 3) |
| opus | `bitrate` **in bits per second** (default 64000 per channel); CELT only; resampled to 48 kHz |
| aiff, au, voc | `sampleFormat` (see each format's `init.luau`) |
| m4a, caf | ALAC (lossless); m4a and caf also keep tags |
Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the format has tags.
## Formats
| Read and write | Read only |
|---|---|
| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC |
Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as
Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see
[music.md](music.md).
## Streaming in a game loop
Decode a little per frame with a time budget. The game never stalls, and memory holds one block, not the whole song.
```luau
local dec = assert(F.audio.open(oggBytes))
local block = buffer.create(1024 * dec.channels * 4)
local queued = 0
-- call once per game frame; returns true at the end of the stream
local function pump(budgetSeconds: number): boolean
local t0 = os.clock()
repeat
local out, n = dec:read(1024, block)
if n == 0 then return true end
queued += n -- hand out[0 .. n * channels * 4) to the audio device here
until os.clock() - t0 >= budgetSeconds
return false
end
while not pump(0.002) do end -- in a game: one pump(0.002) per frame
assert(queued == dec.frames)
```
On LÖVE, `F.host.toSoundData(audioOrDecoder)` makes a `SoundData` (16-bit) for `love.audio.newSource`. A queued
source can be fed block by block:
<!-- doc:display needs LÖVE -->
```lua
local F = require("formats")
local sd = F.host.toSoundData(F.audio.load("music.flac")) -- whole file
love.audio.newSource(sd):play()
local dec = F.audio.open("music.ogg") -- streamed
local q = love.audio.newQueueableSource(dec.sampleRate, 16, dec.channels)
function love.update()
while q:getFreeBufferCount() > 0 do
local out, n = dec:read(4096)
if n == 0 then break end
local part = F.Types.Audio.new(dec.sampleRate, dec.channels, n)
buffer.copy(part.samples, 0, out, 0, n * dec.channels * 4)
q:queue(F.host.toSoundData(part))
end
q:play()
end
```
Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or
visualisers.
## Gotchas
- **Bitrate units differ.** MP3 takes kbps (`bitrate = 192`); Opus takes bits per second (`bitrate = 96000`).
- `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono.
- `read(n, out)` returns a new buffer when `out` is too small. Always use the buffer it returns.
- Opus always decodes at 48 kHz. Resample with `F.ops.audio.resample` if you need another rate.
- `frames` of a VBR stream without an index is an estimate. Count the frames `read` returns if you need the exact
number.
- `F.save(decoder)` without `opts.format` or a destination fails with `Err.ARG`, because a Decoder has no source
format.
- Music files (MOD, S3M, XM, IT, MIDI) are audio too: `F.audio.open` / `F.audio.load` render them, with the
render options in `opts` ([music.md](music.md)).