Browser Game Sound Without Audio Files: Web Audio Recipes
Every Play5s card game effect is generated in the browser with the Web Audio API: a tone with an envelope, a burst of filtered noise and a limiter, and no sample file is downloaded or licensed. The audio context waits for the player's first tap or key, repeats get quieter instead of stacking, and the table colours and patterns come from CSS variables and small inline SVG, also without image files.
This note covers the shared sound module and table backgrounds of the Play5s card games.
Why generate effects instead of shipping files?
A sound file is bytes to download, a licence to track and a decode step before the first play. A card game needs eleven small sounds, each a fraction of a second long, and a recipe for one is a few lines of code. Each effect here lasts under 400 milliseconds, except the win fanfare at about 1.2 seconds.
The one real audio file is an optional music loop under a CC0 public domain dedication. It is fetched only the first time a player switches music on, and music is off until then. Effects are on by default and the choice is remembered in the browser.
What are the two building blocks?
Almost everything is built from a tone and a burst of noise.
A tone is an oscillator, a sine, triangle or square wave, run through a gain node that shapes its loudness. MDN's OscillatorNode page lists the waveforms. The envelope is a quick attack and an exponential decay. An exponential ramp cannot start from zero, so the gain starts at 0.0001, a detail that cost us a silent effect once.
A noise burst makes the paper sounds. The Web Audio API has no noise generator, so the module fills a half-second mono buffer with random samples once, as MDN's advanced techniques guide shows, and plays slices of it through a band-pass filter. Each play starts at a random offset inside the buffer, so two flips in a row never sound identical.
tone(freq, t, dur, { type = 'sine', gain = 0.15, to, attack = 0.004 }) {
const osc = ctx.createOscillator(), g = ctx.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, t);
if (to) osc.frequency.exponentialRampToValueAtTime(to, t + dur);
g.gain.setValueAtTime(0.0001, t);
g.gain.exponentialRampToValueAtTime(gain, t + attack);
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
osc.connect(g).connect(out);
osc.start(t); osc.stop(t + dur + 0.02);
}
noise(t, dur, { freq = 1500, to, q = 1, gain = 0.3 }) {
// noiseBuf: 0.5 s of Math.random() * 2 - 1, built on first use
const src = ctx.createBufferSource(), f = ctx.createBiquadFilter(), g = ctx.createGain();
src.buffer = noiseBuf;
f.type = 'bandpass'; f.frequency.setValueAtTime(freq, t); f.Q.value = q;
if (to) f.frequency.exponentialRampToValueAtTime(to, t + dur);
/* same gain envelope as tone() */
src.connect(f).connect(g).connect(out);
src.start(t, Math.random() * 0.4); src.stop(t + dur + 0.02);
}
What does a card sound like in code?
An effect is one function that schedules a few nodes from a start time. Eleven names are shared by every card game (flip, place, lift, bad, deal, found, run, undo, hint, stuck, win), and a game may add one or two of its own or replace a shared one, as Golf does for its win.
| Name | Heard when | Built from |
|---|---|---|
| flip | A face-down card turns up | 50 ms of noise around 3.2 kHz plus a 30 ms triangle at 1.4 kHz |
| place | A card is laid down | 70 ms of noise around 1.3 kHz plus a sine sliding from 170 to 120 Hz |
| bad | A move is not allowed | Two falling triangle tones, a dull double knock and never a buzzer |
| found | A card reaches its home pile | A small bell: 988 Hz with a quiet octave above it, and a click of noise |
| win | A game is won | C, E and G in turn, then a held C chord, about 1.2 seconds |
Games call sfx('place') from the moment the player does something and nowhere else. Loading a saved game, resizing the window or redrawing the table never play a sound.
When can the browser play sound?
Not at page load. MDN's Web Audio best practices sum up the autoplay policy as: create or resume the context from inside a user gesture. The module takes that literally. It registers capturing listeners for the first pointerdown and keydown on the document, and only then creates the AudioContext and calls resume() inside the same handler. iOS keeps a context silent unless it is resumed inside the gesture.
Until that first tap or key, sfx() returns false and does nothing, which also covers a game that mounts while the tab is in the background. When the tab is hidden the module stops the music, suspends the context, and resumes both when the tab returns, using the Page Visibility API. The autoplay guide explains why browsers hold a context back until the player has acted.
How do you stop fast play from turning into noise?
Autoplay, Finish and a fast keyboard can ask for dozens of effects a second. Four small rules keep that civil:
- One shared limiter. Every effect goes through a master gain of 0.5 and a DynamicsCompressorNode set to a threshold of minus 18 dB, a 12 dB knee, a 6:1 ratio, 3 ms attack and 150 ms release.
- Six voices at most. If six effects are still sounding, the newest request is dropped.
- The same effect cuts itself. A new
placefades the previousplaceout with a 12 ms time constant, and the old voice stops counting against the six. - Repeats get quieter. An effect repeated within 260 ms plays at 0.82 times the previous level, with a floor of 0.3, and after five quick repeats only every other one sounds.
The unit test hands the module a fake browser, with storage, document, audio context, fetch and clock all injected, so these rules run in plain Node without a speaker.
How is the table drawn without image files?
The same idea applies to the table. Every card game puts its look into variables on the game root: --felt, --felt-2 and --felt-3 are the centre, middle and edge of an elliptical light falloff, --felt-pattern is one decorative layer or none, --felt-edge is the frame behind the table, and --slot-* style the empty places where cards can go. A game sets its values once for the light theme and once for the dark one, in its own stylesheet, so one game's colours cannot leak into another's.
| Game | Colours | Motif |
|---|---|---|
| Klondike | #1F7D4E, #17613D, #0F442A | Fibre grain, a faint pick and pan in a corner |
| Spider | #4B2F7A, #36205C, #1E1238 | A web from the top corner and a small spider |
| Scorpion | #DDB66A, #C79D4E, #9C7634 | Low dunes and scorpion tracks |
| Pyramid | #B9754A, #9A5C36, #6E3F22 | Rows of stone blocks and a distant pyramid |
Each motif is one inline SVG under about 2 KB, set as a data URI. In a data URI the SVG uses single quotes and writes # as %23. The Klondike grain is an SVG feTurbulence filter, and the pick and pan are two paths. The rules we follow are simple: one motif with a clear theme per table, placed in a corner or on the edge and never under the main cards, low contrast, a fainter version for the dark theme, and nothing that could be mistaken for a card or an empty place. The light falloff itself is a plain radial gradient.
What did the approach cost?
Audio bytes: none. Table art: a few hundred bytes to 2 KB per game. The costs are elsewhere. Synthesised effects sound like toys, which is why they are short and soft by design. Changing a table's colours means retaking the article screenshots so the page does not describe a green table beside a purple one. And every call site has to resist the urge to play a sound when the game merely redraws.
The reward is that adding a game costs four small jobs: call sfx() at the right events, place the settings button, declare two palettes, and retake the screenshots. You can hear the result in any game on Play5s.