Sound
AudioService is a game's sound: a master gain and four buses (music, sfx, ambient, voice) with their own volumes, sounds defined once by name, sounds that sit in the world (a panner that follows a node; the listener follows the active camera). Browsers refuse sound before the first user action, so the context is made and resumed then (audio:unlocked): loops asked for earlier start at that moment, one-shots asked for earlier are dropped (they would be sounds from the past).
const audio = world.addService(new AudioService());
audio.define('door', { url: 'sounds/door.ogg', spatial: { min: 2, max: 30 } });
audio.play('door', { at: doorEntity.node });
The output#
- Mute.
setMuted(true)silences everything andsetMuted(false)brings back the volumes as they were (audio:muted); a volume changed while muted is kept for the unmute. - Limiter. After the master gain a limiter catches the peaks when many loud sounds come at once (threshold −3 dB, ratio 20: it does nothing to a normal mix).
limiter: falsetakes it out; a compressor's settings ({ threshold, ratio, knee, attack, release }) make it a compressor, as the Falcon demo's −14 dB, 4:1. - Not heard, not played. A positioned one-shot that would reach the listener below
cull(default 0.01 of full) is not made at all (culledcounts them): a hundred guns at the far side of a battle cost nothing. Loops are never culled, since they may come near.
Distance and direction#
spatial is Web Audio's distance model: linear (default; full at min, silent at max), inverse (min / (min + rolloff · (d − min)), never silent: the far guns of a battle) or exponential ((d / min)^−rolloff). distanceGain is the same curve as a function, and reach(at, spatial) the gain a sound there would reach the listener with. A sound that is not positioned can be panned left or right (pan, −1..1; a gun on one side of the player's own ship).
Sound files: WAV and MP3#
define(name, { url }) plays a recording. The browser decodes it (decodeAudioData, which also knows Ogg, Opus and AAC); when it refuses a WAV or MP3, or the platform has no decoder at all (the Unreal build, a test), the engine's own decoder does, so the same two formats play everywhere. new AudioService({ decode }) says who: 'auto' (default), 'browser' or 'engine' (the engine's decoders always: the same samples on every platform, an MP3 cut to the length that was encoded).
audio.define('wind', { url: 'sounds/wind.wav', loop: true, loopPoints: 'file' }); // the loop the WAV file carries (a sound editor's `smpl` chunk)
audio.define('hum', { url: 'sounds/hum.mp3', loop: true, loopPoints: { start: 0.1, end: 0.4 } }); // seconds
audio.fileInfo('sounds/wind.wav'); // { format: 'wav', rate, channels, frames, duration, bits, loops, cues... } once loaded
audio.addFile('pkg://door.wav', bytes); // a file you already hold (a package's): then define({ url: 'pkg://door.wav' })
The same code is a library for tools and tests, with no browser behind it (@ferret/media):
- WAV (
sound-file.ts):readWavInfo(format, length, loops, cue marks and their labels, without reading the samples),decodeWav(PCM 8, 16, 24 and 32 bits, float 32 and 64, A-law, mu-law; mono to many channels; extensible headers; RF64; a streamed file with size -1) andencodeWav(8, 16, 24, 32 bits or float; loops and cue marks written; optional dither). - MP3 (
mp3.ts):readMp3Info(MPEG-1, 2 and 2.5 Layer III: rate, channels, length, bitrate, VBR, the encoder and its delay and padding from the Xing/LAME header; skips ID3v2 and ID3v1 tags and noise between frames),decodeMp3(all block types, mixed blocks, mid/side and intensity stereo, the bit reservoir; gapless by default: the length that was encoded),encodeMp3(constant bitrate, any MPEG rate, joint stereo, a lowpass by bitrate; the Info frame carries the delay and padding, so players cut the file to its exact length). Layers I and II are read but not decoded. The encoder is plain: no block switching, no psychoacoustic model; it reads back at about 18 dB SNR at 128 kbit/s for noisy material and far above for tones, and every decoder plays its files. The decoder equals a reference decoder (mpg123/libsndfile) to float rounding on LAME files of all three MPEG versions. - One door (
sound-io.ts):sniffSound/soundFormatOf(by bytes, or by file name or MIME),soundInfo,decodeSound,encodeSound(pcm, 'wav' | 'mp3'),pcmFromBuffer/bufferFromPcm(Web Audio buffers), andrenderSynth(recipe, { rate, sounds }), which renders a synthesised sound (chains included) with an offline context into samples, so a recipe becomes a file. - Conversions:
toMono,toStereo,resample(windowed sinc, no folding when going down),normalize,trimSilence,sliceSound,peakOf,waveform.
In the asset library a sound is an item with both files and everything a game places it by (see the asset library page); tools/asset-lib/sounds.mjs converts and packs. MP3 has no loop points of its own: a loop is the item's loop (or loopPoints), and the gapless cut makes a whole-file loop seamless for files with an encoder tag. The Unreal exporter writes WAV; Unreal 5 itself plays Ogg/Vorbis, Opus, Bink Audio and ADPCM, and imports no MP3 (only the Windows media player plugin plays it), which is why the engine carries its own MP3 decoder for the native build.
Synthesised sounds#
A sound can be a recipe instead of a recording (SynthRecipe): a few layers, each an oscillator (osc: sine, square, sawtooth, triangle, with freq) or white noise (noise: true), with an optional filter and gain, mixed into an optional shared filter and envelope. It is plain data, so a level can carry it, an editor can change it and an agent can write it; define checks it (validateSynth) and it then plays like any other sound, through its bus, in the world, after the unlock.
Every number of a recipe is one of three things:
- a constant:
freq: 880; - a curve over the sound's time: points
[t, value, ramp]withramplin(default),exp(exponential: the natural fall of a sound; its values must stay above zero) orset(a step);gain: [[0, 0.0001], [0.006, 1, 'exp'], [0.24, 0.001, 'exp']]is a click of an attack and a quick fall; - a live parameter:
{ param: 'throttle', base: 40, scale: 16, smooth: 0.3 }is40 + 16 · throttle, followed with a time constant of 0.3 s when the game sets it.
audio.define('zap', { synth: {
dur: 0.24,
layers: [{ osc: 'sawtooth', freq: [[0, 1500], [0.2, 140, 'exp']] }, { osc: 'square', freq: [[0, 760], [0.22, 90, 'exp']] }],
filter: { type: 'bandpass', freq: [[0, 2400], [0.2, 300, 'exp']], q: 2.5 },
gain: [[0, 0.0001], [0.006, 1, 'exp'], [0.24, 0.001, 'exp']],
} });
A recipe without dur plays until it is stopped: an engine, a wind. Its live parameters are set on the handle while it plays:
const hum = audio.play('engine-hum', { params: { throttle: 0 } });
hum.set('throttle', 0.8); // every frame, from the vehicle
hum.setVolume(0, 0.3); // the engine stops
Chains. delay starts any sound later on the audio clock, exactly (a timer drifts with the frame rate and stops in a background tab). A recipe's then starts more sounds at their times after it, at the same place and pan: the roar of a jump and the boom 1.5 s into it are one sound for the game.
Pass-bys#
Something that comes close and goes away again (a fighter's howl, a shell's whistle, a car going by) fires once on the way in and again only after it has gone far: PassByTrigger is that rule for code that keeps its own positions (check(distance) each frame), and the component PassBy plays its sound from its entity as it passes the listener (sound:passby).
Presets#
SYNTH_PRESETS are ready recipes, from the Falcon demo, number for number: blaster, blaster-light, explosion, explosion-big, missile, shield-hit, flyby, hyperjump (a roar, then explosion-big), alarm and engine-hum (parameter throttle, 0 idle to 1 full, 1.6 with a boost). defineSynthPresets(audio, { names?, prefix?, def? }) registers them. Rendered offline against the demo's hand-written Web Audio graphs they match: the tonal ones exactly (envelope and pitch correlation 1.0, the same level), the noise ones within about 1 dB (their noise is random each time).