Breakout 4: Sound with Web Audio
Turn the sound off in any arcade game and it suddenly feels lifeless. Sound is feedback: it confirms a hit before your eyes have processed it. In this last Breakout step we add sound effects, and we make them without a single audio file: every beep is synthesized by the browser's Web Audio API from an oscillator.
The Web Audio building blocks
Web Audio is a graph of nodes. Sound flows from sources, through processing nodes, to the speakers:
OscillatorNode ──► GainNode ──► audio.destination (speakers)
(a tone) (volume)| Piece | What it does |
|---|---|
new AudioContext() |
the audio engine; create one and reuse it |
audio.createOscillator() |
a tone generator: type ('sine', 'square', 'triangle', 'sawtooth') and frequency in Hz |
audio.createGain() |
a volume knob; gain.value 0 = silent, 1 = full |
audio.currentTime |
the audio clock in seconds; all scheduling uses it |
param.setValueAtTime(v, t) / exponentialRampToValueAtTime(v, t) |
automate a value over time (envelopes, pitch slides) |
osc.start(t) / osc.stop(t) |
play the tone between two times; an oscillator can only be started once |
A beep with an envelope
If you just start and stop an oscillator, you hear clicks at both ends, because the waveform jumps from silence to full volume instantly. A short envelope on the gain fixes it: ramp up in 5 ms, then decay to (almost) zero:
function beep(freq, { dur = 0.08, type = 'square', vol = 0.12, delay = 0, slideTo = 0 } = {}) {
if (!audio || muted) return;
const t = audio.currentTime + delay;
const osc = audio.createOscillator();
const gain = audio.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, t);
if (slideTo) osc.frequency.exponentialRampToValueAtTime(slideTo, t + dur); // pitch slide
gain.gain.setValueAtTime(0.0001, t);
gain.gain.exponentialRampToValueAtTime(vol, t + 0.005); // attack
gain.gain.exponentialRampToValueAtTime(0.0001, t + dur); // decay
osc.connect(gain).connect(audio.destination);
osc.start(t);
osc.stop(t + dur + 0.02);
}Exponential ramps can't reach exactly 0 (the maths involves a logarithm), which is why silence is written 0.0001. Oscillator and gain nodes are cheap and are garbage-collected after stop, so creating two per beep is the normal pattern.
The autoplay rule: sound needs a user gesture
Browsers don't let pages make noise on their own. An AudioContext created before the user has interacted with the page starts suspended and plays nothing. The fix is to create (or resume()) the context inside an input event handler, such as a click or a key press:
let audio = null, muted = false;
function unlockAudio() {
if (!audio) audio = new AudioContext();
if (audio.state === 'suspended') audio.resume();
}
addEventListener('pointerdown', unlockAudio);
addEventListener('keydown', unlockAudio);Our "Click to play" overlay is a gift here: the click that starts the game is also the gesture that unlocks audio.
Note: Don't call
new AudioContext()at the top of your script "just in case". You'll get a suspended context and a console warning, and you still have to resume it from a gesture. Create it lazily, on the first input.
Pitch that tells a story
Each brick in a single rally plays a higher note, and the combo resets when the ball touches the paddle. Climbing pitch rewards long rallies without a word of text. Notes come from the equal-temperament formula f = 440 × 2^(n/12), where n is the number of semitones from A4 (440 Hz). Picking notes from a pentatonic scale keeps any sequence pleasant:
const noteFreq = (semitones) => 440 * 2 ** (semitones / 12);
const PENTATONIC = [0, 2, 4, 7, 9]; // C D E G A
const C5 = 3; // C5 is 3 semitones above A4
function comboNote(combo) {
const octave = Math.floor(combo / PENTATONIC.length);
return noteFreq(C5 + PENTATONIC[combo % PENTATONIC.length] + 12 * octave);
}
console.log("A4:", noteFreq(0), "A5:", noteFreq(12), "A3:", noteFreq(-12));
for (let combo = 0; combo < 7; combo++) {
console.log(`brick ${combo + 1} of the rally: ${comboNote(combo).toFixed(1)} Hz`);
}A4: 440 A5: 880 A3: 220
brick 1 of the rally: 523.3 Hz
brick 2 of the rally: 587.3 Hz
brick 3 of the rally: 659.3 Hz
brick 4 of the rally: 784.0 Hz
brick 5 of the rally: 880.0 Hz
brick 6 of the rally: 1046.5 Hz
brick 7 of the rally: 1174.7 Hz
Twelve semitones is one octave, which doubles the frequency. In the game we cap the combo so the notes don't climb out of hearing range.
The complete Breakout
Everything from Breakout 3 plus sound. Click (this also unlocks audio), ←/→ or A/D, Space to launch, M to mute:
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
// ---- Breakout, step 4: sound effects with Web Audio ----
let audio = null, muted = false;
function unlockAudio() { // must run inside a user gesture
if (!audio) audio = new AudioContext();
if (audio.state === 'suspended') audio.resume();
}
addEventListener('pointerdown', unlockAudio);
addEventListener('keydown', unlockAudio);
function beep(freq, { dur = 0.08, type = 'square', vol = 0.12, delay = 0, slideTo = 0 } = {}) {
if (!audio || muted) return;
const t = audio.currentTime + delay;
const osc = audio.createOscillator();
const gain = audio.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, t);
if (slideTo) osc.frequency.exponentialRampToValueAtTime(slideTo, t + dur);
gain.gain.setValueAtTime(0.0001, t);
gain.gain.exponentialRampToValueAtTime(vol, t + 0.005);
gain.gain.exponentialRampToValueAtTime(0.0001, t + dur);
osc.connect(gain).connect(audio.destination);
osc.start(t);
osc.stop(t + dur + 0.02);
}
const noteFreq = (semitones) => 440 * 2 ** (semitones / 12);
const PENTATONIC = [0, 2, 4, 7, 9];
const comboNote = (c) => noteFreq(3 + PENTATONIC[c % 5] + 12 * Math.floor(c / 5));
const sfx = {
wall: () => beep(300, { dur: 0.04, type: 'triangle', vol: 0.08 }),
paddle: () => beep(196, { dur: 0.07 }),
brick: (combo) => beep(comboNote(Math.min(combo, 9)), { dur: 0.09, type: 'triangle', vol: 0.15 }),
steel: () => beep(1400, { dur: 0.05, type: 'square', vol: 0.05 }),
lose: () => beep(420, { dur: 0.45, type: 'sawtooth', vol: 0.1, slideTo: 70 }),
clear: () => [0, 4, 7, 12].forEach((n, i) => beep(noteFreq(3 + n), { dur: 0.15, type: 'triangle', vol: 0.15, delay: i * 0.1 })),
};
const PADDLE_W = 64, PADDLE_H = 8, PADDLE_SPEED = 320, BALL_SPEED = 230, MAX_ANGLE = Math.PI / 3;
const BRICK_W = 44, BRICK_H = 12, GAP = 2, TOP = 30;
const ROW_COLORS = ['#ef5350', '#ffa726', '#ffee58', '#66bb6a', '#42a5f5', '#ab47bc'];
const TYPES = { '1': { hp: 1 }, '2': { hp: 2 }, '#': { hp: Infinity } };
const LEVELS = [
['1111111111',
'1111111111',
'1111111111'],
['..222222..',
'.21111112.',
'2111111112',
'.21111112.',
'..222222..'],
['##..11..##',
'2222222222',
'1#1#11#1#1',
'1111111111',
'..1....1..'],
];
const paddle = { x: W / 2 - PADDLE_W / 2, y: H - 20 };
const ball = { x: 0, y: 0, size: 6, vx: 0, vy: 0, stuck: true };
let bricks = [], breakable = 0, level = 0, lives = 3, score = 0, combo = 0;
let state = 'playing', stateTimer = 0;
function loadLevel(n) {
level = n;
bricks = [];
const rows = LEVELS[n];
const left = (W - (rows[0].length * (BRICK_W + GAP) - GAP)) / 2;
rows.forEach((line, row) => [...line].forEach((ch, col) => {
if (TYPES[ch]) bricks.push({ x: left + col * (BRICK_W + GAP), y: TOP + row * (BRICK_H + GAP), w: BRICK_W, h: BRICK_H, row, type: ch, hp: TYPES[ch].hp });
}));
breakable = bricks.filter((b) => b.hp !== Infinity).length;
ball.stuck = true;
}
function newGame() {
lives = 3;
score = 0;
loadLevel(0);
state = 'playing';
}
newGame();
function resolve(r) {
const overlapX = Math.min(ball.x + ball.size - r.x, r.x + r.w - ball.x);
const overlapY = Math.min(ball.y + ball.size - r.y, r.y + r.h - ball.y);
if (overlapX <= 0 || overlapY <= 0) return false;
if (overlapX < overlapY) {
if (ball.x + ball.size / 2 < r.x + r.w / 2) { ball.x -= overlapX; ball.vx = -Math.abs(ball.vx); }
else { ball.x += overlapX; ball.vx = Math.abs(ball.vx); }
} else {
if (ball.y + ball.size / 2 < r.y + r.h / 2) { ball.y -= overlapY; ball.vy = -Math.abs(ball.vy); }
else { ball.y += overlapY; ball.vy = Math.abs(ball.vy); }
}
return true;
}
function launch(angle) {
const speed = BALL_SPEED * (1 + 0.12 * level);
ball.vx = speed * Math.sin(angle);
ball.vy = -speed * Math.cos(angle);
}
function play(dt) {
if (keys.has('ArrowLeft') || keys.has('KeyA')) paddle.x -= PADDLE_SPEED * dt;
if (keys.has('ArrowRight') || keys.has('KeyD')) paddle.x += PADDLE_SPEED * dt;
paddle.x = Math.max(0, Math.min(W - PADDLE_W, paddle.x));
if (ball.stuck) {
ball.x = paddle.x + PADDLE_W / 2 - ball.size / 2;
ball.y = paddle.y - ball.size;
if (pressed.has('Space')) { ball.stuck = false; combo = 0; launch(0.35); sfx.paddle(); }
return;
}
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
if (ball.x < 0) { ball.x = 0; ball.vx = Math.abs(ball.vx); sfx.wall(); }
if (ball.x + ball.size > W) { ball.x = W - ball.size; ball.vx = -Math.abs(ball.vx); sfx.wall(); }
if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); sfx.wall(); }
if (ball.vy > 0 && ball.y + ball.size > paddle.y && ball.y < paddle.y + PADDLE_H &&
ball.x + ball.size > paddle.x && ball.x < paddle.x + PADDLE_W) {
ball.y = paddle.y - ball.size;
const offset = (ball.x + ball.size / 2 - (paddle.x + PADDLE_W / 2)) / (PADDLE_W / 2);
launch(Math.max(-1, Math.min(1, offset)) * MAX_ANGLE);
combo = 0;
sfx.paddle();
}
const i = bricks.findIndex((b) => resolve(b));
if (i !== -1) {
const brick = bricks[i];
brick.hp--;
if (brick.type === '#') sfx.steel();
else { sfx.brick(combo); combo++; }
if (brick.hp <= 0) { bricks.splice(i, 1); breakable--; score += 20; }
else if (brick.type !== '#') score += 5;
if (breakable === 0) { state = 'cleared'; stateTimer = 1.5; sfx.clear(); }
}
if (ball.y > H) {
lives--;
sfx.lose();
if (lives === 0) state = 'lost';
else ball.stuck = true;
}
}
function update(dt) {
if (pressed.has('KeyM')) muted = !muted;
const confirm = pressed.has('Enter') || pressed.has('Space');
if (state === 'playing') play(dt);
else if (state === 'cleared') {
stateTimer -= dt;
if (stateTimer <= 0) {
if (level + 1 < LEVELS.length) { loadLevel(level + 1); state = 'playing'; }
else state = 'won';
}
} else if (confirm) newGame();
}
function brickColor(b) {
if (b.type === '#') return '#78809a';
if (b.type === '2') return b.hp === 2 ? '#e0e0e0' : '#9e9e9e';
return ROW_COLORS[b.row % ROW_COLORS.length];
}
function draw() {
ctx.fillStyle = '#0e1018';
ctx.fillRect(0, 0, W, H);
for (const b of bricks) {
ctx.fillStyle = brickColor(b);
ctx.fillRect(Math.round(b.x), Math.round(b.y), b.w, b.h);
}
ctx.fillStyle = '#e8eaf6';
ctx.fillRect(Math.round(paddle.x), Math.round(paddle.y), PADDLE_W, PADDLE_H);
if (state === 'playing') {
ctx.fillStyle = '#ffffff';
ctx.fillRect(Math.round(ball.x), Math.round(ball.y), ball.size, ball.size);
}
ctx.fillStyle = '#b0b6cc';
ctx.font = '12px ui-monospace, monospace';
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
ctx.fillText(`SCORE ${score}`, 8, 8);
ctx.textAlign = 'center';
ctx.fillText(`LEVEL ${level + 1}/${LEVELS.length} · SOUND ${muted ? 'OFF' : 'ON'} (M)`, W / 2, 8);
ctx.textAlign = 'right';
ctx.fillText('♥'.repeat(lives), W - 8, 8);
if (state === 'playing' && ball.stuck) {
ctx.fillStyle = '#5c6380';
ctx.textAlign = 'center';
ctx.fillText('Space to launch', W / 2, H - 46);
}
if (state === 'cleared') banner(`Level ${level + 1} cleared!`, level + 1 < LEVELS.length ? 'Get ready…' : '');
if (state === 'won') banner('You win!', `Score ${score} · Enter to play again`);
if (state === 'lost') banner('Game over', `Score ${score} · Enter to try again`);
}
run(update, draw, '←/→ or A/D · Space to launch · M mutes');
</script>Design notes
- An
sfxobject gives every sound a name (sfx.paddle(),sfx.lose()). Game code says what happened; the sound design lives in one place, easy to tweak or replace with recorded samples later. - Different events, different timbres. Walls are a soft triangle wave, the paddle a low square wave, steel a short high "tink". Players learn to tell them apart without looking.
- The level-clear jingle is four notes scheduled ahead of time with
delay: Web Audio's clock is sample-accurate, far more precise thansetTimeout. - Mute is a requirement, not a feature. People play at work, on trains and next to sleeping babies. Make it one key, and show its state on screen.
beepreturns early whileaudioisnull, so the game never crashes before the first gesture. It just plays silently.
Tip: Recorded sounds work the same way:
fetchthe file,await audio.decodeAudioData(buffer), then play it with anAudioBufferSourceNodeconnected to a gain node. Libraries such as Howler.js wrap this (plus sprite sheets of sounds and format fallbacks); the lessons in this course stay with synthesized sound so every game works offline.
Test yourself
When can a page start playing Web Audio sound?
- As soon as the script loads
- After a user gesture such as a click or key press creates or resumes the AudioContext
- Only after
setTimeout(..., 1000) - Only in fullscreen mode
Why ramp the gain up and down instead of starting and stopping the oscillator at full volume?
- It is louder
- A sudden jump in the waveform produces an audible click; a short envelope avoids it
- Oscillators can't stop otherwise
- To save CPU
With f = 440 × 2^(n/12), what happens to the frequency when n grows by 12?
- It adds 12 Hz
- It doubles: one octave higher
- It halves
- Nothing