Sound Plugin
Hybrid synth + sampler + tracker audio plugin for Clayground. One coherent
engine, two wrappers for pre-existing assets (Sound, Music), and a
small instrument/sequencer layer on top (SynthInstrument,
SampleInstrument, SongPlayer, SfxPlayer, ChipMood/MoodPlayer). Offline render
is first-class and deterministic.
See docs/docs/manual/dojo.md for how to hot-reload song files without
resetting the playhead (.dojoignore).
Getting Started
import Clayground.Sound
Components
Sound
For short sound effects (fire-and-forget). Supports overlapping playback with instance pooling for efficiency.
Sound {
id: jumpSound
source: "sounds/jump.wav"
volume: 0.8
lazyLoading: false // preload by default
}
// Usage
onJumped: jumpSound.play()
onReset: jumpSound.stop() // stops all playing instances
Music
For background music with full playback controls.
Music {
id: bgMusic
source: "music/theme.mp3"
volume: 0.5
loop: true
}
// Usage
onGameStarted: bgMusic.play()
onGamePaused: bgMusic.pause()
onGameOver: bgMusic.stop()
Properties
Sound
| Property | Type | Default | Description |
|---|---|---|---|
source |
url | ”” | Audio file URL (local or remote) |
volume |
real | 1.0 | Volume level (0.0-1.0) |
lazyLoading |
bool | false | If true, load on first play() |
loaded |
bool | readonly | Whether audio data is loaded |
status |
enum | readonly | Null/Loading/Ready/Error |
Music
| Property | Type | Default | Description |
|---|---|---|---|
source |
url | ”” | Audio file URL |
volume |
real | 1.0 | Volume level (0.0-1.0) |
lazyLoading |
bool | false | If true, load on first play() |
loaded |
bool | readonly | Whether audio data is loaded |
playing |
bool | readonly | Currently playing |
paused |
bool | readonly | Currently paused |
loop |
bool | false | Loop playback |
position |
int | readonly | Current position (ms) |
duration |
int | readonly | Total duration (ms) |
SynthInstrument
Real-time oscillator voice with ADSR, pitch envelope, LFO, a pulse width
for square and a resonant filter with its own cutoff envelope. Trigger
notes by MIDI number or Hz. Also bakes to WAV.
SynthInstrument {
id: lead
waveform: "square" // sine | square | triangle | sawtooth | noise
pulseWidth: 0.25 // square only, 0.05..0.95; 0.5 = plain square
attack: 0.005; decay: 0.08; sustain: 0.5; release: 0.15
// Filter, off by default: none | lowpass | highpass | bandpass
filterType: "lowpass"; cutoff: 400; resonance: 0.3
// Cutoff envelope: +3 octaves at its peak, decaying back to 400 Hz
filterEnvAmount: 3; filterDecay: 0.2; filterSustain: 0
volume: 0.8
pan: -0.3 // -1 left .. +1 right; 0 = centred
bus: "music" // sfx (default) | music | voice
}
// Fire a note
lead.triggerNote(69, 0.9, 0.25)
// Synth-to-sample bounce
var wavPath = lead.bake(69, 0.4)
SampleInstrument
PCM sample playback with loop points, root note, ADSR on top of samples.
SampleInstrument {
id: drum
source: "kick.wav"
rootNote: 60
volume: 0.9
interpolation: "gaussian" // nearest | linear (default) | gaussian (soft, SNES-like)
maxVoices: 4 // a fifth note cuts the oldest; 0 (default) = no cap
}
drum.triggerOneShot(0.8)
maxVoices exists on SynthInstrument too.
SongPlayer
Plays a .song.json against QML instruments resolved by objectName.
Supports play/pause/stop/seek/loop and hot-reload without playhead reset.
SynthInstrument { id: lead; objectName: "demoLead" }
SynthInstrument { id: bass; objectName: "demoBass" }
SongPlayer {
source: "songs/demo.song.json"
instruments: [lead, bass]
loop: true
onHotReloaded: console.log("song file changed, kept playing")
}
Song file format (v1):
{
"tempo": 110,
"tracks": {
"lead": { "instrument": "demoLead" },
"bass": { "instrument": "demoBass" }
},
"patterns": {
"A": {
"lead": [
{ "t": 0, "note": "C5", "dur": 0.5 },
{ "t": 0.5, "note": "E5", "dur": 0.5 }
],
"bass": [{ "t": 0, "note": "C3", "dur": 2.0 }]
}
},
"sections": [ { "pattern": "A", "repeat": 4 } ]
}
Notes can be MIDI numbers or scientific pitch strings (C4, F#3, Bb5).
Defaults: dur=0.5 beats, vel=0.8.
volume (0..1, default 1) scales every note the player triggers, on
whichever instrument, also while the notes ring: animate it to fade a song.
renderOffline(seconds) renders the song on an engine of its own with the
instruments’ current patches, the player’s volume and loop: mono
samples at 44.1 kHz, every note on its exact frame (live, a note starts on
the 10 ms tick it falls into). seconds 0 renders the song’s length.
Song v2: the instruments in the file, music that follows the game
A file with "version": 2 is complete on its own - it defines the
instruments its tracks play - and has the structure adaptive game music
needs. demo/songs/adaptive.song.json uses all of it:
{
"version": 2, "tempo": 120, "beatsPerBar": 4,
"instruments": {
"lead": { "source": "triangle", "envelope": { "attack": 10, "release": 120 }, "gain": -10 },
"bass": { "source": "sawtooth", "filter": { "type": "lowpass", "cutoff": 700 }, "gain": -12 },
"kick": { "source": "sample", "sample": "kick.wav", "root": "C2", "bus": "music" }
},
"tracks": { "melody": { "instrument": "lead" }, "bass": { "instrument": "bass" } },
"patterns": { "Explore": { ... }, "Combat": { ... }, "Pickup": { ... } },
"segments": {
"explore": { "sections": [ { "pattern": "Explore" } ] },
"combat": { "sections": [ { "pattern": "Combat", "repeat": 2 } ], "exits": [4] }
},
"start": "explore",
"layers": { "drive": { "tracks": ["arp", "hat"], "intensity": [0.25, 0.75], "fade": 4 } },
"transitions": [
{ "from": "explore", "to": "combat", "sync": "bar" },
{ "from": "combat", "to": "explore", "sync": "exit", "stinger": "pickup" }
],
"stingers": { "pickup": { "pattern": "Pickup", "sync": "beat" } }
}
- Instruments take an effect recipe layer’s fields and units (
source,envelopein ms,pitch,filter,pulseWidth,lfo(a sine onpitchorvolume; noshape, nocutoff),gainin dB up to 0,pan) plusbus(defaultmusic) andmaxVoices, with a recipe layer’s defaults for what is left out: no attack, decay or release, full sustain, linear segments, 0 dB, centred. The segment curves are a recipe’s too (see “Segment curves” below). A sample instrument names itssample(a WAV relative to the song file), itsrootnote,interpolationandloop(trueor{ "start", "end" }as fractions). Every track plays a defined instrument;instrumentson the player is not read. - Segments are the parts the music moves between. A segment plays its
sections, then
next(itself by default). A v2 pattern lasts whole bars. Withoutsegmentsthe sections are one segment,main, after which the song ends, or starts again withloop; such a song needs at least one section. - Exits are beats into a segment where a transition synced to
exitmay leave it. - Layers are tracks that sound only as loud as the intensity lets them:
silent at or below the first number, full at or above the second (one
number: full from there). A change of intensity moves a layer’s level
over
fadebeats; each note plays at the level its start falls on. - Transitions say how the music moves from one segment to another
(
from/toleft out: any), synced to the nextbeat,bar,exitor the segment’send, optionally with a stinger where the new segment starts. The first that matches wins; without one, the next bar. - Stingers play a pattern once on top of the music, on their sync.
- Echo (not in the demo song; the lines below give it one) is the SNES
echo of the song: the bus echo of “Echo and reverb per bus” below, with
the same fields, ranges and defaults:
delayin ms (1..1000, default 120),feedback(-1..1, 0.5),volume(0..1, 0.5) and up to 8firtaps (newest sample first, missing ones 0; default[1]). As on the SNES, where the echo is switched per voice, only thetrackslisted feed it; left out, every track does. -
Reverb is the small reverb of a bus, over every track of the song and the echo’s repeats:
roomSize,dampingandvolume, 0..1, defaults 0.5, 0.5 and 0.3."echo": { "delay": 176, "feedback": 0.45, "volume": 0.4, "fir": [0.4, 0.3, 0.2, 0.1], "tracks": ["melody", "arp"] }, "reverb": { "roomSize": 0.6, "damping": 0.4, "volume": 0.2 }Both are the song’s own: they play on the music bus beside the dry tracks, which sound exactly as without them, and before the bus volume and the bus effects. Live playback and
renderOffline()render the same samples with them, and a song withoutechoandreverbrenders as before they existed. Stopped, the tail rings out; a reload starts both from silence. - Output
"output": "snes"(not in the demo) plays the song through the SNES-style output of every bus its instruments play on (see “SNES output per bus” below): 32 kHz and the soft top end of the chip’s gaussian."clean", the default, leaves the buses as they are. It is set when the song starts playing, and an offline render has it from the first frame, so both give the same samples.
SongPlayer {
id: music
source: "songs/adaptive.song.json"
state: game.fighting ? "combat" : "explore" // moves on its transition's sync
intensity: game.danger // 0..1, fades the layers
}
// music.playStinger("pickup")
segment is the segment playing now, position the beats into it and
totalBeats its length. Set before play(), state and intensity are
where the song starts. A v2 song’s notes are scheduled 0.25 s
(kScheduleAheadFrames) ahead of the engine on their exact frames, so a
control reaches the music that much later and its playhead moves while the
engine renders - through the sink, or on the engine’s own clock where no
output device opens (see below). renderOffline(seconds, cues) takes the
same path: from the player’s state and intensity, steered by cues such as
[{ at: 2, state: "combat" }, { at: 3, intensity: 1 }, { at: 4, stinger: "pickup" }]
(at in seconds), it renders the samples live playback renders for the
same controls at the same song frames, the song’s echo and reverb included.
A v1 song plays as before.
SfxPlayer and effect recipes
An effect recipe (*.sfx.json) describes a sound effect as a stack of
layers - each one voice with a source, an envelope, a pitch curve, a filter
curve, a start offset, a gain and a pan - in physical units: Hz, ms,
semitones, dB. A variation spec makes every play a little different:
SfxPlayer {
id: detent
source: "sfx/wheel-detent.sfx.json"
}
var seed = detent.play() // the next variation; returns its seed
detent.play(0.6) // the same at velocity 0.6 (all layers)
detent.play(1, 7) // a fifth up (all layers, semitones)
detent.playSeed(seed) // that variation again
var mono = detent.renderOffline(seed) // what play() of that seed sounded like
detent.stop() // end what it still plays
With loop: true a play repeats its variation until stop() - an ambience
bed that plays on with no seam:
SfxPlayer { id: wind; source: "sfx/wind.sfx.json"; loop: true }
var seed = wind.play() // pass after pass, until stop()
var two = wind.renderOffline(seed, 1, 0, 2) // two passes of the loop
The wheel detent of demo/sfx/ (lock_picker’s, four layers):
{
"version": 1,
"name": "wheel-detent",
"variation": { "seed": 1, "pool": 6 },
"layers": [
{ "name": "tick", "role": "transient", "source": "noise",
"length": 6, "gain": -10.46,
"envelope": { "attack": 0.5, "decay": 9, "sustain": 0, "release": 4 } },
{ "name": "body", "role": "body", "source": "triangle",
"freq": 783.99, "length": 40, "gain": -10.03,
"envelope": { "attack": 0.5, "decay": 55, "sustain": 0, "release": 20 },
"pitch": { "start": 12, "end": 0, "time": 12 },
"vary": { "detune": [-1, 1] } },
{ "name": "glint", "role": "tail", "source": "sine",
"freq": 2793.83, "length": 50, "gain": -21.94,
"envelope": { "attack": 0.5, "decay": 70, "sustain": 0, "release": 30 },
"vary": { "detune": [-1, 1] } },
{ "name": "weight", "role": "body", "source": "sine",
"freq": 123.47, "length": 45, "gain": -13,
"envelope": { "attack": 1, "decay": 55, "sustain": 0, "release": 20 },
"pitch": { "start": 7, "end": 0, "time": 20 } }
]
}
Top level: version (1), name, variation, maxVoices (see “Bursts”
below), layers (required, at least one). A layer:
| Field | Unit | Default | Meaning |
|---|---|---|---|
source |
- | required | sine, square, triangle, sawtooth, noise or sample |
name, role |
- | - | a label; role is transient, body or tail |
freq |
Hz, 1..20000 | 440 | pitch of an oscillator layer; the clock of a noise layer with "rate": "freq" |
detune |
semitones, -48..48 | 0 | shifts freq, or a sample’s pitch |
gain |
dB, -96..12 | 0 | level of the layer |
pan |
-1..1 | 0 | added to the player’s pan |
offset |
ms, 0..10000 | 0 | start after play() |
length |
ms, 0..10000 | required (oscillators) | the gate; the release runs inside it. A sample without one plays to its end |
envelope |
attack, decay, release in ms; sustain 0..1; attackCurve, decayCurve, releaseCurve 0..1 |
0, 0, 0; 1; 0, 0, 0 | ADSR, each segment with its curve; a sample layer takes attack and release and their curves only |
pitch |
start, end in semitones; time in ms; curve 0..1 |
0 | a sweep from start to end over time |
filter |
type; cutoff Hz; resonance 0..1; attack, decay, release ms; sustain 0..1; amount octaves; attackCurve, decayCurve, releaseCurve 0..1 |
-, 1000, 0, 0, 0, 0, 1, 0, 0, 0, 0 | lowpass, highpass or bandpass, with a cutoff envelope that moves the cutoff by amount octaves at its peak |
pulseWidth |
0.05..0.95 | 0.5 | square only |
lfo |
target; shape; rate Hz, 0..100; depth semitones (pitch), 0..1 (volume) or octaves (cutoff) |
-, sine, 0, 0 |
target pitch, volume or cutoff; shape sine, square, sample_hold or smooth_random (see “LFO”) |
noise |
color: white, pink, brown; rate: sample, freq |
white, sample |
noise only (see “Noise”) |
fm |
ratio 0.01..64; index radians, 0..32; attack, decay, release ms; sustain 0..1; attackCurve, decayCurve, releaseCurve 0..1 |
required, required; 0, 0, 0; 1; 0, 0, 0 | two-operator FM with an index envelope (see “FM and ring”); oscillator layers only |
ring |
ratio 0.01..64 |
required | ring modulation (see “FM and ring”); oscillator layers only, not with fm |
drive |
dB, 0..48 | - (off) | saturates the layer through a tanh (see “Drive and crush”); any source |
crush |
bits 1..24; rate Hz, 20..192000 |
24, 192000 (each off) | rounds the layer to bits and holds each value for one period of rate (see “Drive and crush”); any source; needs one of the two |
sample, interpolation |
path; nearest, linear, gaussian |
-, linear |
the WAV of a sample layer, relative to the recipe file |
burst |
count 1..256; duration ms; density 0.01..100; jitter: time 0..1, gain dB, cutoff octaves, freq semitones, length ms |
required, required, 1; 0, 0, 0, 0, 0 | the layer plays as count short grains inside duration (see “Bursts”); not on a sample layer |
vary |
{"<field>": [min, max]} |
- | per play, min..max is added to the field |
Segment curves: every envelope segment - attack, decay and release of the
amplitude and the cutoff envelope - and the pitch sweep has a curve from 0,
linear (the default, as before curves existed), to 1, exponential.
Exponential is how a struck object rings out: the distance left to the
segment’s target falls by 60 dB over the segment’s time, a straight line in
dB, so a decay or release to 0 ends at -60 dB and its time is its RT60. An
attack rises fast and settles into the peak; a pitch sweep moves fast and
settles into its end, a kick’s or a hit’s drop. Values between mix the two
shapes. For an impact or a ring, "decay": 400, "sustain": 0, "decayCurve": 1
falls evenly in dB over its 400 ms; a linear decay of the same time stays
loud for most of it and drops off at the end.
Noise: a noise layer is white noise drawn every sample unless its noise
group says otherwise - the default sounds as noise did before the group
existed, and ignores freq.
{ "name": "rumble", "source": "noise", "freq": 600, "length": 900,
"noise": { "color": "brown", "rate": "freq" } }
color:whiteis flat,pinkfalls 3 dB per octave,brown6 dB. Pink and brown sit about 6 dB below white, so their peaks stay inside -1..1 as white’s do.rate:sampledraws a new value every sample.freqholds each value for one period of the layer’s pitch -freqraised bydetune, thepitchsweep and a pitchlfo- as the SNES noise clock does: the spectrum is that of the colour laid over the clock, and a quarter of thefreqlays it two octaves lower. White noise clocked at 8000 Hz has half of its power below about 2150 Hz, at 2000 Hz below about 540 Hz. Since the clock is the pitch, everything that moves a pitch moves a clocked noise: a play’sdetune,vary.detune,burst.jitter.freq, a pitch sweep (a falling hiss). A clock above the sample rate draws every sample.- The colour is shaped at the clock: the colour filters run once per drawn value, so pink and brown keep their slope below a clock of any rate.
FM and ring: metal hits, bells and sparkle have partials that are not
whole multiples of one pitch, and one oscillator through a filter cannot
make them. A layer without an fm or a ring group sounds as layers did
before the groups existed. Both run inside the layer’s voice - a modulator
of the layer, not one layer modulating another - and both follow the
layer’s pitch: freq raised by detune, the pitch sweep and a pitch
lfo, so a play’s detune moves the partials with it.
{ "name": "bell", "source": "sine", "freq": 500, "length": 1800,
"envelope": { "decay": 1800, "sustain": 0, "decayCurve": 1 },
"fm": { "ratio": 2.76, "index": 6, "decay": 1200, "sustain": 0.1, "decayCurve": 1 } }
fm: a sine modulator atratiotimes the layer’s pitch moves the phase the wave is read at by up toindexradians. On a sine that puts sidebands atfreq + n * ratio * freqfor every wholen, then-th pair at|J_n(index)|of the plain sine’s level; the ones below 0 Hz fold back (at 500 Hz and 1:2.76: 500, 880, 1880, 2260, 3260, … Hz).index0 is the plain wave; 1 gives the first pair at 0.44, 2 at 0.58 and the second pair at 0.35. A wholeratiokeeps the partials harmonic, another one makes them inharmonic. On square, triangle and sawtooth the same phase shift is applied to the richer wave.- The index has an envelope of its own, an ADSR as the cutoff’s:
indexis its peak,sustaina fraction of it, the times in ms with their curves. Withoutattackanddecayand withsustain1, the defaults, the index holds. A decaying index narrows the spectrum as it falls - the power-weighted spread around the carrier isindex * ratio * freq / sqrt(2)Hz - which is how a struck bar or bell loses its brightness before its level. ring: the layer’s wave times a sine atratiotimes its pitch, before the filter. On a sine that leaves the sum and the difference of the two, each at half the level, and neither of them (500 Hz and 1:2.76: 880 and 1880 Hz).- Nothing is band-limited: sidebands above half the sample rate fold back
as aliases, so a high
indexon a highfreqsounds grainy. - A layer takes one of the two, on
sine,square,triangleorsawtooth;noiseandsampletake neither.varyand macros reach every number of both (vary: {"fm.index": [-1, 1]}).
LFO: growls, fire flicker and organic wobble move at random, not on a
sine. A layer’s lfo moves one target by up to depth either way at
rate Hz, on the wave its shape names; without a shape it is the sine
it was before the field existed.
{ "name": "flicker", "source": "noise", "length": 1500,
"filter": { "type": "bandpass", "cutoff": 900, "resonance": 0.3 },
"lfo": { "target": "cutoff", "shape": "smooth_random", "rate": 7, "depth": 1.5 } }
target:pitchmoves the layer’s pitch bydepthsemitones,volumetakes up todepth(0..1) off the envelope,cutoffmoves the filter’s cutoff bydepthoctaves on top of its envelope - so it needs afilter. Each is the LFO’s value, -1..1, timesdepth: a cutoff of 900 Hz at depth 1.5 moves between 318 and 2546 Hz.shape:sinestarts at 0 and rises.squareis +1 for the first half of each period and -1 for the second, with hard edges - onvolumea hard gate that clicks.sample_holdholds one random value, -1..1, for each period of1 / rateseconds and jumps to the next.smooth_randompasses through the same values as each period starts and glides from one to the next over the period (a raised-cosine step, so it neither jumps nor kinks).- The random values are drawn from the play’s seed, as a noise layer’s
are: the same
variation.seedand play renders the same samples, every burst grain draws values of its own, and a pool of variations gives each one other values. A layer has no seed of its own for its LFO. varyand macros reachrateanddepth; a design file’s override setslayers[<layer>].lfo.shape.
Drive and crush: explosions and growls need saturation, chip sounds their
grit. A layer without a drive or a crush sounds as layers did before
the two existed. Both act on what the layer sounds after its envelope and
before its gain, so gain stays the layer’s output level and does not
change how hard it is driven or how coarse its steps are; a play’s
velocity, too, only scales the result.
{ "name": "growl", "source": "sawtooth", "freq": 90, "length": 900,
"filter": { "type": "lowpass", "cutoff": 700, "resonance": 0.4 },
"drive": 18, "crush": { "bits": 6, "rate": 8000 } }
drive: the signal raised bydrivedB into atanh. On a sine that adds odd harmonics and no even ones, and keeps every peak inside -1..1. On a full-scale sine: 0 dB is already a soft clip, the third harmonic at 0.05 of the peak; 6 dB 0.19, 12 dB 0.34, 24 dB 0.42, the fifth at 0.04, 0.14, 0.24. There is no make-up gain: a quiet layer driven hard comes out louder, so lower itsgainto match.crush.bitsrounds every value to a step of2^(1 - bits)of full scale: a full-scale sine at 4 bits takes the 17 levels -1, -0.875, …,bitsmay be fractional, so a macro moves it smoothly; 24, the default, rounds nothing.
crush.rateholds each value for1 / rateseconds, as a lower sample rate would: at 11025 Hz under a 44.1 kHz output every value four samples, at 3000 Hz 14 or 15. The steps fold the layer back around multiples ofrate, unfiltered - the aliasing is the grit. A rate at or above the output’s, as the default 192000, holds nothing.- The order inside a layer is drive, then hold, then rounding. Nothing is band-limited: the harmonics a high drive adds above half the sample rate fold back too.
varyand macros reachdrive,crush.bitsandcrush.rate(vary: {"drive": [-3, 3]}).
Bursts: crumble, gravel, crackle and debris are many tiny grains with
random timing. A layer with a burst plays as count grains instead of one
note, each grain the layer itself - its source, envelope, filter, length,
gain - started at its own time inside the duration after the layer’s
offset:
{ "name": "grit", "source": "noise", "offset": 5, "length": 3, "gain": -4,
"envelope": { "decay": 3, "sustain": 0 },
"filter": { "type": "bandpass", "cutoff": 1400, "resonance": 0.2 },
"burst": { "count": 23, "duration": 420, "density": 0.2,
"jitter": { "time": 1, "gain": 3, "cutoff": 0.5, "length": 1 } } }
- Grain
iofnowns the slot[i, i + 1) / nof the burst and starts in its middle;jitter.timemoves it up to that fraction of half the slot either way, so at 1 a grain starts anywhere in its slot. The grains keep their order, and every one starts inside theduration. densityis the grain rate at the burst’s end over the rate at its start, the change between them exponential: 1 (the default) spreads the grains evenly, 0.2 starts them five times as densely as it ends - a crumble that thins out - and 5 is the reverse.- The other jitters move each grain’s
gain(dB),filter.cutoff(octaves), pitch (semitones, asdetune) andlength(ms) by a random amount up to that much either way.jitter.cutoffneeds afilter. A grain stays inside the field’s range: its gain at most 12 dB, itsdetunewithin -48..48, its cutoff within 20..20000 Hz, its length at least 0 - a jitter that reaches past an edge plays those grains at it. - Every grain’s times and jitters, and its noise, are hashed from the
play’s seed, the layer and the grain’s number alone: the same seed plays
the same grains, another seed other ones. A layer’s
varyis drawn once per play and holds for all its grains;varycan move the burst’s numbers too (burst.count,burst.jitter.gain), and a fractionalcountplays the nearest whole number of grains.
maxVoices (top level, 0..256, default 0 = no cap) bounds the grains of
the recipe’s bursts that ring at once: a grain that would exceed it cuts the
oldest grain still ringing, with no fade. It counts the grains of every play
of the player, and only grains: the recipe’s other layers never count
against it and are never cut. A recipe with a cap needs a burst.
vary names a numeric field by its path: detune, gain, envelope.decay,
envelope.decayCurve, filter.cutoff, pitch.start, pitch.curve,
fm.index, ring.ratio, drive, crush.bits, burst.count,
burst.jitter.time, …
Every value a range can reach must be a valid value of that field. The
parser rejects an unknown field by name and path (layers[1].envelope:
unknown field 'decya'), and so does a hot reload, which keeps playing the
last good recipe.
Variation: variation.seed (default 0) is the base of every variation seed,
and variation.pool cycles play() through that many variations; without a
pool every play() is a new one. The n-th play() uses
variationSeed(n), and a seed always draws the same values: each varied
field takes min + (max - min) * u, with u in [0, 1) hashed from the
seed, the layer and the field with integer arithmetic. Noise layers get a
seeded noise sequence the same way.
play() and renderOffline() schedule the same notes through the same
code, so renderOffline(seed) returns the samples play() of that seed
sends into its bus - at the player’s volume and pan, as the mono
(L + R) / 2 downmix, from the first layer’s start to the last layer’s end.
What the bus adds afterwards (its volume, echo and reverb) is not part of
it. volume, pan and bus work as on the instruments.
All three take a detune in semitones after the velocity - play(velocity,
detune), playSeed(seed, velocity, detune), renderOffline(seed, velocity,
detune) - which transposes every layer, oscillator and sample alike: the
play renders the samples of the same recipe with every layer’s detune
raised by that much. An effect a game plays on a scale (rising coins, one
tone per tumbler) is one recipe.
stop() ends every voice the player started: a ringing layer runs its own
envelope.release from that moment and is freed, a layer whose offset has
not come yet does not start. A long recipe - an ambience bed when the level
changes - thus ends within its longest release, and the next play() works
as before.
A looped recipe (loop: true, read by play()) plays the notes of the seed
it drew pass after pass, until stop(). A pass starts one period after the
one before: the period is the time until the last layer ends, less that
layer’s envelope.release. The release of one pass thus crossfades into the
next pass, and a last layer without a release is followed by the next pass on
the next sample - no gap either way. Whether the seam is smooth is the
recipe’s: give the layers an envelope.attack as long as the release (a
linear fade-out over a linear fade-in of the same sound keeps the level), or
none at all on noise. renderOffline(seed, velocity, detune, passes) of a
looping player renders passes periods (default 1) of the same loop; the
second of two passes is the loop as a file, steady from its last sample to
its first. A play() while a loop plays replaces it, and a hot reload of a
looping player loops the new recipe on.
SfxPlayer watches its recipe file and hot-reloads it; add sfx/ (or
*.sfx.json) to the sandbox’s .dojoignore.
Design files: templates, macros and overrides
A recipe is what a game plays; a design file is what a sound designer, or
an agent, works on. It names a template - a recipe whose layers are the
defaults, plus a few macros, knobs that each move several parameters at
once - sets the macros, and writes overrides on top. The engine library
compiles it to the flat *.sfx.json; SfxPlayer only ever reads the
compiled file, so a game knows nothing of macros.
The template demo/sfx/wheel-detent.sfx.template.json is the wheel detent
above with three macros (its layers shortened here):
{
"version": 1,
"template": { "id": "wheel-detent", "version": 1 },
"name": "wheel-detent",
"variation": { "seed": 1, "pool": 6 },
"layers": [ { "name": "tick", ... }, { "name": "body", ... },
{ "name": "glint", ... }, { "name": "weight", ... } ],
"macros": [
{ "id": "weight", "label": "Weight", "range": [0, 1], "default": 0.5,
"drives": [
{ "path": "layers[body].freq", "from": 1108.73, "to": 554.37, "curve": "exp" },
{ "path": "layers[weight].freq", "from": 174.61, "to": 87.31, "curve": "exp" },
{ "path": "layers[weight].gain", "from": -19, "to": -7 } ] },
{ "id": "click", "label": "Click", "range": [0, 1], "default": 0.5,
"drives": [
{ "path": "layers[tick].gain", "from": -16.46, "to": -4.46 },
{ "path": "layers[glint].gain", "from": -27.94, "to": -15.94 } ] },
{ "id": "ring", "label": "Ring", "range": [0, 1], "default": 0.5,
"drives": [
{ "path": "layers[body].envelope.decay", "from": 27.5, "to": 110, "curve": "exp" },
{ "path": "layers[glint].envelope.decay", "from": 35, "to": 140, "curve": "exp" } ] }
]
}
and demo/sfx/wheel-detent-heavy.sfx.design.json a design on it, which
compiles to the committed demo/sfx/wheel-detent-heavy.sfx.json:
{
"version": 1,
"name": "wheel-detent-heavy",
"template": { "id": "wheel-detent", "version": 1 },
"macros": { "weight": 0.9, "click": 0.8, "ring": 0.7 },
"overrides": { "layers[glint].gain": -26 },
"locks": ["weight"]
}
A template is a valid recipe - version, name, variation, layers as
above - plus:
| Field | Meaning |
|---|---|
template |
required: id (a string) and version (an integer from 1) |
macros |
the knobs, in the order a tool shows them |
meta |
any object, for what tools keep beside the format (provenance, a licence); the compiler ignores it |
A macro:
| Field | Meaning |
|---|---|
id |
required: letters, digits, _ and -, not starting with a digit; unique in the template |
label |
what a knob shows; the id when absent |
range |
required: [min, max], min below max |
default |
required: inside the range |
drives |
required, may be empty: [{path, from, to, curve}] - from is the value at the range’s min, to at its max |
A drive’s curve is lin (default: from + (to - from) * t), exp
(from * (to / from)^t, for Hz and ms; from and to non-zero and of one
sign) or db (from and to in dB, the value written is 10^(dB / 20):
a level in 0..1, such as envelope.sustain, moved evenly by ear), with t
the macro’s place in its range from 0 to 1. A drive’s path is a layer’s
number in the vary syntax behind a layer selector: layers[1].gain,
layers[body].envelope.decay, layers[grit].burst.count - an index, or the
name of exactly one layer.
The field must have a meaning on its layer (no filter.cutoff without a
filter), and a path is driven by one macro only.
At its default a macro’s drives must pass through the values the layers
have (to 0.01 %; layers[0].gain: at the macro's default 0.5 it gives -3,
but layers[0].gain is -6 otherwise): a template is its own recipe at the
default macro values.
A design file:
| Field | Meaning |
|---|---|
template |
required: the id and version of the template it is for; another version does not compile |
name |
the compiled recipe’s name; the template’s when absent |
macros |
{"<id>": value}, each inside its macro’s range; a macro not named stays at its default |
overrides |
{"<path>": value}: name, variation.seed, variation.pool, maxVoices, or any field of a layer - layers[2].gain, layers[body].filter.type, layers[body].vary.detune, layers[grit].burst.jitter.time - or a whole group (layers[0].envelope, layers[grit].burst.jitter). null removes the field. Two overrides may not write into each other (layers[0].filter and layers[0].filter.cutoff) |
locks |
macro ids and paths the tools must leave alone; the compiler checks they name one and otherwise ignores them |
meta |
any object (lineage, a target); the compiler ignores it |
The compiled recipe is the template’s recipe with the design’s name, then
its overrides, then every driven path the overrides leave alone. An override
wins over the macro that drives its path, whatever the macro’s value. A
macro at its default writes nothing, so the template’s value stays exactly
as written; at any other value its drives go through their curves and are
rounded to six significant digits, so a last-bit difference between two
platforms’ pow() never reaches the file. A driven value outside what the
recipe accepts there - the field’s range, less the layer’s vary range for
it, a volume lfo’s depth at most 1 - is clamped to the edge and reported,
not written as is - at a macro’s default too, when an override (a wider
vary range) leaves the template’s value outside. An override’s value is not clamped: a recipe the parser
rejects is an error (the compiled recipe: layers[0].gain: 50 is outside
-96..12). Both parsers reject an unknown field by name and path
(macros[0]: unknown field 'lable', overrides: unknown path
'layers[0].gian'), as the recipe parser does.
The compiled file is written in one form - the keys in a fixed order
(version, name, variation, layers; in a layer name, role,
source first), a layer field per line, numbers in their shortest exact form -
so the same template and design give the same bytes, on every platform.
In C++ (see “The engine without QML”):
cs::SfxCompileResult heavy;
std::string error;
cs::compileDesignFile("sfx/wheel-detent-heavy.sfx.design.json",
"sfx/wheel-detent.sfx.template.json",
"sfx/wheel-detent-heavy.sfx.json", &heavy, &error);
for (const QString &line : heavy.clampMessages()) ... // what was clamped
for (const auto &d : heavy.drives) ... // each drive: macro, path, value, written, clamped, overridden
SfxDesignCompiler::parseTemplate(), parseDesign() and compile() take
the files’ bytes instead; writeSfxRecipe() writes any recipe in the
compiled form. A game ships the compiled *.sfx.json, not the design;
setting a macro while a game runs is not part of this.
Stereo, pan and buses
The engine mixes in stereo. Every instrument (SynthInstrument,
SampleInstrument, Sound) has a pan from -1 (left) to +1 (right) and a
bus: "sfx" (default), "music" or "voice". Centred, the default, plays
the same samples in both channels that the mono engine played; panning turns
the far channel down (at pan: 0.5 the left plays at half level). The
SoundMixer singleton holds one volume per bus, on top of each instrument’s
own:
SoundMixer.musicVolume = 0.4 // every instrument with bus: "music"
SoundMixer.sfxVolume = 1.0
SoundMixer.voiceVolume = 0.8
Music (the QMediaPlayer-based type) does not play on the engine, but it
follows the music bus: it plays at its volume times SoundMixer.musicVolume.
Muting a process: CLAY_SOUND_MUTE
With CLAY_SOUND_MUTE=1 in the environment, every output clay_sound opens
plays at volume 0: the shared sink that Sound, SampleInstrument,
SynthInstrument, SongPlayer and SfxPlayer play through, SoftSynth’s
sink and Music’s audio output. Everything still plays - voices start,
SongPlayer.playing turns true, SfxPlayer.play() returns its seed - and an
offline render does not change. Use it for tests, benches and flow checks
that should not play through the speakers. A sink reads the variable when it
opens, so set it before the first sound plays; Music reads it whenever its
volume is applied. SoundMixer and the players’ volume properties keep
reading what was set.
Without an output device
Where no output device opens - a machine without one, such as a CI runner,
or one whose devices all fail to open - the engine that Sound,
SampleInstrument, SynthInstrument, SongPlayer and SfxPlayer play on
runs on a clock of its own: it renders in real time and the samples go
nowhere. Everything that follows the engine moves as it would with a device:
a song’s playhead, its segment following its state on the sync point,
its transitions and stingers, voices that start and end. Nothing is heard,
with or without CLAY_SOUND_MUTE. Every later note tries the devices again,
at most twice a second, and the first that opens takes over from where the
clock is. SoftSynth and Music have outputs of their own and do not run
on this clock.
Echo and reverb per bus
Every bus has an echo and a small reverb, both off by default; a bus with neither on sounds exactly as before. The echo is the SNES one: a delay line whose output runs through an 8-tap FIR filter, is added to the bus and is fed back into the line. A low-pass FIR makes every repeat darker than the one before - the warm SNES echo. The reverb is a small Schroeder reverb (four damped combs and two allpasses per channel).
SoundMixer.musicEcho.enabled = true
SoundMixer.musicEcho.delay = 120 // ms, 1..1000
SoundMixer.musicEcho.feedback = 0.5 // -1..1, each repeat this times the last
SoundMixer.musicEcho.volume = 0.5 // 0..1, level of the echo on the bus
SoundMixer.musicEcho.fir = [0.25, 0.25, 0.25, 0.25] // 8 taps, missing ones 0
SoundMixer.sfxReverb.enabled = true
SoundMixer.sfxReverb.roomSize = 0.5 // 0..1, length of the tail
SoundMixer.sfxReverb.damping = 0.5 // 0..1, how fast the highs die
SoundMixer.sfxReverb.volume = 0.3 // 0..1
The default taps [1, 0, 0, 0, 0, 0, 0, 0] pass the delayed signal as is,
so repeat n plays at volume * feedback^(n-1), n * delay after the
note. The taps are consecutive samples at the engine’s 44.1 kHz (the SNES
ran its FIR at 32 kHz), so a SNES coefficient set filters at somewhat
higher frequencies here. The echo runs before the reverb, and both before
the bus volume. Turning an effect off drops its tail; on again, it starts
from silence. The effects play the same way live and in an offline render.
SNES output per bus
The SNES played everything at 32 kHz, and every sample went through the S-DSP’s gaussian interpolation, which takes the top end off softly. Every bus can sound like that, after its echo and its reverb: the mix is resampled to 32 kHz through that gaussian and brought back to the engine’s rate with nothing above 16 kHz. Measured with tones at 44.1 kHz: -0.07 dB at 1 kHz, -4.3 dB at 8 kHz, -6.8 dB at 10 kHz, -11 dB at 12 kHz, -19 dB at 14 kHz, nothing left at its own frequency from 16 kHz up; what lies above folds down quietly, as on the chip (18 kHz comes out at 14 kHz, -28 dB). The bus sounds 16 frames (0.36 ms) later with it on.
A version 2 song turns it on with "output": "snes"; in C++ it is
engine.snesOutput(Bus::Music).start(frame), the 32 kHz grid starting at
frame, or setEnabled(true). Off, the default, the bus renders exactly
the samples it did before.
Two song players on one bus share its SNES output: the last one to play
sets it. A player turns off what it turned on when it goes or loads a
song without "output": "snes", but only if no player started it since;
stop() leaves it on, so the tail rings out through it. The rule is the
engine’s: start(frame) returns a token, and release(token) turns the
output off only if nobody started it again, or switched it on with
setEnabled(true), after that start. setEnabled(true) on an output
already on keeps its 32 kHz grid where it is and still counts as such a
start. On the adaptive demo song it takes 15 dB off
above 10 kHz and leaves what lies below 4 kHz within 0.05 dB.
The engine without QML
A C++ program links the engine as Clayground::SoundEngine - a static
library that needs Qt Core only, no QML, no Multimedia, no audio device -
and includes clay_sound_engine.h. A project that builds clayground with
add_subdirectory(../clayground ...), as shapes-and-stone does, gets the
target with it.
target_link_libraries(my_renderer PRIVATE Clayground::SoundEngine)
#include "clay_sound_engine.h"
namespace cs = clay::sound;
cs::RecipeFile detent; // the recipe and its samples
cs::loadRecipe("sfx/wheel-detent.sfx.json", &detent);
auto fx = cs::renderRecipe(detent.recipe, detent.samples, seed,
1.0f, 1.0f, 0.0f, cs::kSampleRate, false);
cs::writeWav("detent.wav", fx, 1, cs::kSampleRate);
cs::SongModel song;
cs::loadSong("songs/demo.song.json", &song);
cs::SongInstruments inst; // by the names the tracks bind
inst["demoLead"].synth.waveform = cs::OscillatorVoice::Waveform::Triangle;
inst["demoBass"].synth.waveform = cs::OscillatorVoice::Waveform::Sawtooth;
auto music = cs::renderSong(song, inst, 0.0, 1.0f, false, cs::kSampleRate, false);
cs::writeWav("song.wav", music, 1, cs::kSampleRate, cs::WavFormat::Pcm16);
| Call | Does |
|---|---|
loadRecipe(path, &file, &error) |
parses a *.sfx.json and decodes its sample layers, each relative to the recipe |
compileDesignFile(design, template, recipe, &result, &error) |
compiles a design file against its template and, with a recipe path, writes the compiled *.sfx.json there (see “Design files”) |
loadSong(path, &model, &error) |
parses a .song.json; a v2 song’s sample instruments get their WAVs decoded, each relative to the song |
renderRecipe(recipe, samples, seed, velocity, gain, pan, rate, stereo, seconds, detune) |
the samples SfxPlayer.renderOffline(seed, velocity, detune) returns at that volume and pan; seconds 0 = until the last layer ends, detune 0 = as written |
renderSong(model, instruments, seconds, volume, loop, rate, stereo) |
the samples SongPlayer.renderOffline(seconds) returns; seconds 0 = the song’s length |
renderSong(model, performance, seconds, volume, loop, rate, stereo) |
a v2 song on its own instruments, from performance.start at performance.intensity, each of performance.cues (state, intensity or stinger) at its song frame: what live playback renders for the same controls; seconds 0 = one pass of the start segment; with the song’s output |
writeWav(path, samples, channels, rate, format, &error) |
32-bit float (default, the samples exactly) or 16-bit wav; stereo samples interleaved |
A v1 song names its instruments but does not define them, so the program
gives each name an InstrumentSpec: the patch of a SynthInstrument
(synth, an OscillatorVoice::Patch) or the sample, root note and patch
of a SampleInstrument, with gain (the QML volume), pan, bus and
maxVoices. The same seed or the same song and instruments render the same
samples as the QML players on the same machine - tst_clay_sound_outside
compares the two sample for sample. A v2 song defines its instruments, so it
needs no SongInstruments; SongSequencer hands out its notes on frames
for a program that schedules them itself. As in the QML offline renders, a v2
song’s own echo and reverb are applied and the bus volume, echo and reverb are
not.
Platform Support
- WASM: full support — the same QAudioSink-driven engine as desktop,
through Qt Multimedia’s emscripten backend.
Musicgoes its own way there, see “Musicon WASM” below. - Desktop/Mobile: Full support — all types above work end-to-end.
Music on WASM: it plays, and reports almost nothing
On the web a Music track plays: the bytes are fetched, written to the
browser’s in-memory filesystem and handed to an HTML <audio> element.
Qt’s WebAssembly media backend only ever plays what it can open as a local
file, so a qrc: or http(s) source has to take that detour — handing it
the URL directly routes it to a video output that does not exist and takes
the whole page down (#261).
What that costs, on the web and only there (measured with Qt 6.10.1 in Chrome):
- A user gesture is required first. A
play()before the first click or key press is refused by the browser, and Qt does not catch that refusal — it surfaces as an uncaughtplay() failed because the user didn't interact with the document firstin the console. .mp3, not.wav. The backend labels a staged.wavblobaudio/vnd.wave, a type Chrome declines, and the track stays silent.positionanddurationstay0loophas no effect — the track plays once, thenfinishedfiresstatusdoes reachReady
A background loop on the web therefore needs the finished signal or a
Sound re-triggered by a Timer at the clip length (see #216).
Two of those points were re-measured on Qt 6.11.1 and did not move (#264):
position stays 0 through a 30 s track, and status reaches Ready. The
user-gesture rule, the .wav MIME refusal and loop were not re-tested on
6.11.1. Which Qt the web runtime is built with, and why, is pinned and
argued in .github/workflows/main.yml.
Technical Notes
- Audio is fully preloaded before playback (no streaming)
- WASM: Web Audio API requires user gesture to start AudioContext. An
AudioContext created before the first click is resumed on that click by
wasm/gesture.pre.js: emscripten’s own listeners wait for amousedownthe browser never sends for a click on a Qt window, and a page whose sound started before the click stayed silent (#480) - WASM, Qt before 6.11.1: Qt resumes and closes a throwaway AudioContext
for every audio device and drops the promise
resume()returns; before a click, Chrome 156 rejects it (“AudioContext closed before a pending resume() could complete”).wasm/resume.pre.js, linked into every app on such a Qt, catches exactly those rejections (#480) - WASM: Remote URLs must be CORS-enabled
- Desktop: Uses
QAudioSinkfor all in-engine types,QMediaPlayerforMusic - Hot-reload:
SongPlayerandSfxPlayerwatch their source file; drop a.dojoignore(songs/,sfx/or*.song.json) next to yourSandbox.qmlto prevent the dojo from reloading the whole scene on edits