audio
Garnet Audio
An owner-driven stereo mixer and optional default-device output backed by vendored miniaudio 0.11.23. Use the mixer alone for headless and offline work.
cmake -S audio/native -B audio/native/build -DCMAKE_BUILD_TYPE=Release
cmake --build audio/native/build --parallel
Create an immutable Sound from normalized interleaved Float32 samples, decode a short memory-backed WAV, FLAC, or MP3 via Sound.decode(bytes), or read one from a Garnet::Content::Source with Sound.load(source). Requiring the shard registers a default "sound" importer for .wav, .flac and .mp3 (see content). A Mixer plays sounds on nested gain buses and supports stop, seek, pitch, pan, loop points and sample-clock scheduling. Loop bounds are zero-based source frame indices with an exclusive end. render advances the output sample clock and drain_events returns finished or stopped voices with their frame numbers. Drain completions regularly to free voice capacity.
A Device opens on its owner thread. Pump PCM from the mixer before starting and regularly during playback. The native callback reads a preallocated single-producer ring and fills underruns with silence. Read consumption and underrun counters with stats. stop suspends consumption and start resumes with the queued PCM. Call close before disposing of the owner. Voice completion refers to rendered frames. The device may still have queued audio.
mixer = Garnet::Audio::Mixer.new
mixer.play(sound)
device = Garnet::Audio::Device.new
begin
device.pump(mixer)
device.start
# Call device.pump(mixer) from the application's frame loop.
ensure
device.close
end
Use Mixer#play_stream(path, bus: music, loop: true) for long WAV, FLAC, or MP3 files, or pass a Garnet::Content::Source instead of a path. A FileSource is checked against its revision and then streamed from its path; other sources are read into memory once when the voice starts and decoded incrementally from that copy. Stream voices share the mixer's bus, pan, gain and output clock. buffer_frames bounds each voice's decoded buffer. seek uses frames at the mixer sample rate, and whole-file looping is available. Pitch and custom loop points are available on Sound voices. A stream read error emits a Failed completion. Call mixer.close on its owner thread to release active decoders.
The optional scene binding supplies listener-relative gain and pan. Platform device-change orchestration remains open. Scene binding
Positional audio without a scene
Create a SpatialMixer over a Mixer, set its listeners, and play sounds with a world-space Position and audible range. Each listener supplies a normalized right axis. Listener.from_yaw is a convenience for Z-up scenes. With several listeners, the strongest attenuation determines level and stereo direction is weighted by each listener's audibility. A SpatialCue can schedule a delay in seconds or as a Time::Span. Use SpatialMixer#place to update a moving voice, or call Mixer#play directly for music, UI, and custom DSP control.
Everything that takes a Position also takes a Garnet::Math::Vec3 (Position#to_vec3 converts back), and ranges accept any Number. Gain, pan and pitch arguments on Mixer, Output and SpatialMixer accept any Number too, so mixer.play(sound, gain: 0.5) needs no _f32.
The mixer runs on its creating thread. Device#pump fills an output buffer on that thread and the native audio callback consumes it independently. Mixer#render writes to a caller-provided buffer for offline or custom output.
Audio plugin
require "garnet-audio/plugin" adds engine-managed audio to a Garnet::World:
world.add_plugin(Garnet::Audio::Plugin.new)
world.schedule.add(:update, name: "sfx") do |w, _|
output = w.resource(Garnet::Audio::Output)
cue = output.play(chime, :effects, gain: 0.8_f32)
w.events(Garnet::Audio::CueFinished) { |done| } # finished, stopped or failed
end
Output queues commands (play, stream, stop, gain, pan, pitch, volume(channel, gain) and send { |engine| } for anything else) and returns a Cue immediately. Cues play on Channel buses (master, music, effects, ambience, dialogue). play takes a delay: in seconds or as a Time::Span.
Spatial cues on Output
output.listeners = {Garnet::Audio::Listener.from_yaw(hunter_eye, hunter_yaw)}
cue = output.play_at(roar, boss_position, range: 30, gain: 0.8, delay: 0.1, voice_limit: 96)
hum = output.play_at(engine_loop, truck_position, :ambience, loop: true)
output.place(hum, truck_position, range: 24) # each frame the truck moves
The World sends listener and emitter positions; placement runs on the mixer thread with SpatialMixer's falloff. When the listeners change, the mixer re-places every playing play_at cue. A cue that no listener hears, that finds no free voice, or that would exceed voice_limit: playing voices, finishes at once as CompletionKind::Skipped. loop: true cues keep playing silently out of range. Audio.mix_at(listeners, position, range) predicts the same placement on the World thread. Several listeners mix by the loudest level, as with SpatialMixer. Audio::Scene builds on this.
send blocks receive the mixer thread's Engine: engine.bus(channel), engine.spatial, engine.mixer, and any other Mixer method, which the engine forwards (send { |mixer| mixer.voice_count } still works).
Headless output for tests
Audio::Headless is an Output without a device or thread. Queue commands on headless.output, then headless.render(frames) runs them and returns the interleaved samples; #events returns completions, #recording = true keeps every rendered sample in #recorded. Audio::Plugin.new(device: false) mixes through one, reachable as plugin.headless, and headless.last is the block the latest Audio phase rendered.
Thread ownership:
- World thread: systems call
Output. Theaudio.outputsystem (Audiophase) hands the frame's commands over and emitsCueFinishedandOutputErrorevents. Nothing on this side touches the mixer or device. - Mixer thread (default): a dedicated thread creates and exclusively owns the
MixerandDevice. It runs commands, keeps the device queuelatencydeep (64 ms by default) everyperiod(5 ms), drains completions and starts or stops the device. Frame hitches or paused simulation don't starve the device. - Host events: the plugin subscribes to
Garnet::Lifecycle, soSuspend/AudioInterruptedstop the device andResume/AudioRestoredrestart it as soon as the driver reports them, between frames if needed.Closeand world close join the thread.
Audio::Plugin.new(device: false) (or GARNET_AUDIO=off) keeps the mixer on the world thread and renders exactly one frame of samples per Audio phase, for deterministic tests and captures. If no device can open, the mixer thread keeps the clock running in real time and emits an OutputError. Output#stats, #sample_clock and #device_running? report the mixer thread's state as of the last Audio phase. Use Output#play_at for spatial audio; a SpatialMixer of your own must live in send blocks, on the mixer thread.
audio
- 0
- 0
- 0
- 1
- 4
- 2 days ago
- November 30, 2026
MIT License
Thu, 03 Dec 2026 02:10:59 GMT