Files
rosetta/examples/music.luau
T
2026-11-01 01:49:44 -05:00

33 lines
1.7 KiB
Luau

-- examples/music.luau: write a MIDI file, read it back, render it to audio (docs/guide/music.md).
local F = require("@rosetta")
-- 1. a Midi: 480 ticks per quarter note, absolute ticks, a tempo, a track name and a little melody
local midi = F.Types.Midi.new(480)
local events = {
{ tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- 500000 us per beat = 120 BPM
{ tick = 0, type = "meta", meta = 0x03, data = { string.byte("Melody", 1, -1) } }, -- the track name
{ tick = 0, type = "program", channel = 0, data = { 0 } },
}
local tick = 0
for _, note in { 60, 62, 64, 65, 67, 67, 69, 67 } do
table.insert(events, { tick = tick, type = "noteOn", channel = 0, data = { note, 96 } })
tick += 240 -- an eighth note
table.insert(events, { tick = tick, type = "noteOff", channel = 0, data = { note, 0 } })
end
table.insert(midi.tracks, { events = events })
-- 2. save as .mid and read it back
local bytes = assert(F.save(midi, nil, { format = "midi" }))
local song = assert(F.music.load(bytes))
print(string.format("midi: %d bytes, type %d, %d track(s), \"%s\", %.1f s at %d BPM", buffer.len(bytes), song.format,
#song.tracks, tostring(song.tracks[1].name), song.meta.length, song.meta.tempos[1].bpm))
assert(song.meta.length == 2)
-- 3. render: a Decoder (stereo f32), turned into an Audio, then saved as WAV
local dec = song:render({ sampleRate = 22050, tail = 0.5 })
local audio = assert(F.ops.audio.toAudio(dec))
local peak = F.ops.audio.peak(audio)
local wav = assert(F.save(audio, nil, { format = "wav" }))
print(string.format("rendered: %.2f s, peak %.2f, %d bytes of WAV", audio.frames / audio.sampleRate, peak, buffer.len(wav)))
assert(audio.frames == 2.5 * 22050 and peak > 0)