17 KiB
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.
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 rosetta
local quieter = F.ops.audio.gainDb(song, -6)
local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192000 })) -- 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:
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.
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). Options:
| Option | Formats | Meaning |
|---|---|---|
format |
all | decode as this format ("mp3", "wav", ...) and skip detection |
maxFrames |
wav, flac, mp3, aiff, au, voc, aac, mpc, ac3 | Err.LIMIT past this many frames |
drc |
ac3 | dynamic range control: 0 = off (default), 1 = as the stream says |
stereo |
opus | downmix surround streams to stereo |
sbr |
aac, m4a, the AAC tracks of mp4 / mkv / ts | false: decode only the AAC-LC core of HE-AAC (half the rate, mono for HE-AACv2, about 4x faster) |
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)
HE-AAC
HE-AAC (SBR) and HE-AACv2 (SBR + parametric stereo) decode at the full output rate in every AAC path: ADTS, M4A,
and the audio tracks of MP4, Matroska and MPEG-TS (HLS radio). ADTS cannot signal SBR, so the decoder looks for SBR
and PS data in the first frames, as ffmpeg does; sampleRate, channels and frames report the output.
local dec = assert(F.audio.open(heAacBytes)) -- HE-AACv2 in ADTS: a 24 kHz mono core
assert(dec.sampleRate == 48000 and dec.channels == 2) -- SBR doubles the rate, PS makes it stereo
local core = assert(F.audio.open(heAacBytes, { sbr = false })) -- the AAC-LC core only, for slow devices
assert(core.sampleRate == 24000 and core.channels == 1 and core.frames * 2 == dec.frames)
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" |
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.
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)
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 (default 128000; one of the layer's rates), layer 3 or 2 (MP2), mode = "stereo" | "joint" | "mono", sampleRate, id3, resampleQuality |
| vorbis | quality -1..10 (default 3) |
| opus | bitrate (default 64000 per channel, 6000..510000); 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 |
| adx, vag | loop = { start, stop } (frames; default the source's meta.source.loop) |
| adpcm | codec = "ima" | "ima_wav" | "ms", blockAlign (block codecs), lowFirst (ima nibble order) |
bitrate is in bits per second for every encoder (bitrate = 192000), as the Decoder's bitrate field is. A
value below 1000 is read as kbit/s (bitrate = 192 is 192000), so older code that passed kbit/s to MP3 still works.
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), qoa, adx, vag, adpcm (raw IMA / MS) | aac (ADTS; AAC-LC, HE-AAC, HE-AACv2), m4a / caf AAC, mpc (Musepack SV7 / SV8), ac3 (Dolby Digital), brstm / bcstm / bfstm, KVAG, wav / aifc / caf IMA and MS ADPCM, wavpack (.wv + .wvc), ape, tta |
Each format's capabilities are listed in FORMATS.md. The audio tracks of video files open as
Decoders too: see v.audio in video.md. Music files (MOD, MIDI, ...) render to a Decoder: see
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.
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:
local F = require("rosetta")
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.
Musepack and AC-3
Musepack (.mpc, stream versions 7 and 8) decodes gapless, with its APEv2 tags. AC-3 (.ac3, Dolby Digital) decodes
every channel layout up to 5.1 without downmixing, in WAVE order (FL FR FC LFE SL SR), with dynamic range control off
unless drc asks for it. The AC-3 tracks of MKV, MP4, MPEG-TS and AVI files open as v.audio the same way. Both
seek exactly (Musepack SV7 like libmpcdec: 32 frames of pre-roll). E-AC-3 (Dolby Digital Plus) is Err.UNSUPPORTED.
local mpc = assert(F.audio.load(mpcBytes)) -- Musepack: tags, exact length
assert(F.detect(mpcBytes) == "mpc" and mpc.tags.title == "Docs Tone")
assert(mpc.frames == 44100 and mpc.meta.source.version == 8)
local dd = assert(F.audio.open(ac3Bytes)) -- AC-3 5.1: a Decoder like any other
assert(dd.channels == 6 and dd.sampleRate == 48000)
dd:seek(0.25)
local _, n = dd:read(256)
assert(n == 256)
local stereo = assert(F.ops.audio.downmix(F.audio.load(ac3Bytes))) -- 2 channels, ITU-R BS.775
local night = assert(F.audio.load(ac3Bytes, { drc = 1 })) -- the stream's dynamic range gains applied
assert(stereo.channels == 2 and night.channels == 6)
Game audio and ADPCM
Console and game engines store sound as 4-bit ADPCM or QOA: small, and cheap to decode while the game runs. They load
and save like any other audio. Loop points (ADX, VAG, BRSTM) come out in meta.source.loop (and dec.loop), in
frames, stop exclusive; the encoders write them back.
local tone = F.Types.Audio.new(22050, 1, 22050) -- 1 s of 440 Hz
for i = 0, tone.frames - 1 do
buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(2 * math.pi * 440 * i / 22050))
end
local qoa = assert(F.save(tone, nil, { format = "qoa" })) -- Quite OK Audio: 3.2 bits per sample, as qoa.h writes it
assert(F.detect(qoa) == "qoa" and F.audio.load(qoa).frames == tone.frames)
local adx = assert(F.save(tone, nil, { format = "adx", loop = { start = 0, stop = tone.frames } })) -- CRI ADX
local looped = assert(F.audio.load(adx))
assert(looped.meta.source.loop.stop == tone.frames)
local vag = assert(F.save(tone, nil, { format = "vag" })) -- PlayStation VAG (mono VAGp; stereo is VAGi)
assert(F.audio.load(vag).frames >= tone.frames) -- + the blank frame VAGs start with, and frame padding
A raw ADPCM stream has no header, so the layout comes from the options, and only opts.format or the .adpcm / .ima
extension finds it:
local raw = assert(F.save(tone, nil, { format = "adpcm", codec = "ima" })) -- 4 bits per sample
local back = assert(F.audio.load(raw, { format = "adpcm", codec = "ima", sampleRate = 22050, channels = 1 }))
assert(back.frames == tone.frames)
Read only: Nintendo BRSTM / BCSTM / BFSTM (DSP ADPCM or PCM; F.detect names the flavour), KVAG, and the ADPCM
inside WAV (IMA, MS), AIFF-C and CAF (ima4). Decoding is bit-exact with vgmstream (ADX, VAG, BRSTM) and ffmpeg
(IMA, MS, ima4, QOA). Seeking is exact everywhere: the decoders keep the predictor state of every block they pass.
Lossless: WavPack, Monkey's Audio, TTA
WavPack (.wv), Monkey's Audio (.ape) and TTA (.tta) open and load like FLAC. Their tags (APEv2) come out in
tags with lower-case keys. Integer streams also have readInt, which returns the exact samples as i32. Every
frame of these formats is independent, so seek lands on the exact sample.
local wv = assert(F.audio.open(wvBytes))
assert(wv.bitsPerSample == 16 and wv.lossless and wv.tags.title == "Docs Tone")
local exact, n = wv:readInt(1024) -- i32 samples, as wvunpack writes them
assert(n == 1024 and buffer.readi32(exact, 0) == 0)
local ape = assert(F.audio.load(apeBytes)) -- any level, fast .. insane
assert(ape.meta.source.format == "ape" and ape.tags.artist == "rosetta")
local tta = assert(F.audio.open(ttaBytes))
tta:seek(0.5)
assert(math.abs(tta:position() - 0.5) < 1e-6)
A hybrid WavPack file holds a lossy stream. Its .wvc correction file makes it lossless again. Pass the correction
file as correction. When you load a file by path, the .wvc next to it is found automatically. Without it, the
file decodes lossy.
local lossy = assert(F.audio.open(hybridWvBytes))
local full = assert(F.audio.open(hybridWvBytes, { correction = hybridWvcBytes }))
assert(lossy.hybrid and not lossy.lossless and full.lossless)
local song = assert(F.audio.load("assets/tone_hybrid.wv")) -- reads assets/tone_hybrid.wvc too
assert(song.meta.source.correction == true)
Gotchas
F.ops.audio.downmix(a)defaults to 2 channels, so a stereo input stays stereo. Usedownmix(a, 1)for mono.read(n, out)returns a new buffer whenoutis too small. Always use the buffer it returns.- Opus always decodes at 48 kHz. Resample with
F.ops.audio.resampleif you need another rate. framesof a VBR stream without an index is an estimate. Count the framesreadreturns if you need the exact number.F.save(decoder)withoutopts.formator a destination fails withErr.ARG, because a Decoder has no source format.- Music files (MOD, S3M, XM, IT, MIDI) are audio too:
F.audio.open/F.audio.loadrender them, with the render options inopts(music.md).