Files
rosetta/examples/audio.luau
T

48 lines
2.3 KiB
Luau

-- Audio example (rosetta): build a sound, edit it with F.ops.audio, encode it to several formats, then stream it
-- back with a Decoder. Run from the repository root: luau examples/audio.luau (docs/guide/audio.md explains the API).
local F = require("@rosetta")
local A = F.ops.audio
-- 1. one second of a stereo chord: interleaved f32 samples, frame i / channel c at byte (i * channels + c) * 4
local rate = 22050
local tone = F.Types.Audio.new(rate, 2, rate)
for i = 0, tone.frames - 1 do
local t = i / rate
buffer.writef32(tone.samples, (i * 2) * 4, 0.3 * math.sin(2 * math.pi * 261.63 * t)) -- left: C4
buffer.writef32(tone.samples, (i * 2 + 1) * 4, 0.3 * math.sin(2 * math.pi * 329.63 * t)) -- right: E4
end
tone.tags = { title = "Example chord", artist = "rosetta" }
-- 2. edit: fade, normalize, a mono copy at 16 kHz, then the two one after the other
local shaped = assert(A.normalize(assert(A.fade(tone, 0.05, 0.2)), 0.8))
local mono = assert(A.resample(assert(A.downmix(shaped, 1)), 16000))
local both = assert(A.concat({ shaped, mono })) -- mono is converted to stereo 22.05 kHz
print(string.format("edited: %d frames, %.2f s, peak %.2f", both.frames, both.frames / both.sampleRate, (A.peak(both))))
-- 3. encode: lossless and lossy
for _, fmt in { "wav", "flac", "mp3", "vorbis", "opus" } do
local opts = { format = fmt }
if fmt == "mp3" or fmt == "opus" then opts.bitrate = 128000 end -- bit/s (values below 1000: kbit/s)
local bytes = assert(F.save(both, nil, opts))
local dec = assert(F.audio.open(bytes))
print(string.format("%-6s %6d bytes %5d Hz %d ch %.2f s title=%s", fmt, buffer.len(bytes), dec.sampleRate, dec.channels,
dec.duration, tostring(dec.tags.title)))
assert(math.abs(dec.duration - 2) < 0.1)
end
-- 4. stream a FLAC back in blocks, reusing one buffer, and measure its level
local dec = assert(F.audio.open(assert(F.save(both, nil, { format = "flac" }))))
local block = buffer.create(512 * dec.channels * 4)
local frames, sumSquares = 0, 0
while true do
local out, n = dec:read(512, block)
if n == 0 then break end
for k = 0, n * dec.channels - 1 do
local s = buffer.readf32(out, k * 4)
sumSquares += s * s
end
frames += n
end
assert(frames == both.frames)
print(string.format("streamed %d frames, rms %.3f", frames, math.sqrt(sumSquares / (frames * dec.channels))))