Game sounds

A game sound is one line. There are fourteen, ready-made: coin, jump, laser, shoot, explosion, hit, powerup, blip, click, zap, bounce, pop, win and lose.

playSound("coin")

Put the line where the thing happens:

if (star.touches(basket)) {
  score += 1
  playSound("coin")
}

A whole game with a sound

const ball = new Sprite("⚽", 200, 100, 48)
ball.vy = 0

function onMouseDown() {
  ball.vy = -600
}

function update(dt) {
  ball.vy += 900 * dt
  ball.update(dt)
  if (ball.y > height - 24) {           // the ground
    ball.y = height - 24
    if (ball.vy > 60) playSound("bounce")
    ball.vy = -ball.vy * 0.8
  }
}

function draw() {
  background("seagreen")
  ball.draw()
}

The ball makes a sound each time it lands. Click or tap to throw it up again. The sound is asked for only when the ball is falling fast, so a ball at rest is quiet.

Louder, higher, to one side

A second value is how loud: 1 is as it comes, 0.5 is half. The rest go by name.

playSound("coin", 0.5)                        // half as loud
playSound("laser", { pitch: 5, pan: -1 })     // five semitones higher, on the left
playSound("win", { after: 0.5 })              // half a second from now
playSound("win", { length: "half" })          // cut short, or its last note held, to last half a note
OptionWhat it does
pitchMoves the sound up or down, in semitones
panWhere it is, from -1 (left) to 1 (right)
lengthHow long it lasts: a number is seconds, a name is a note length
after, at, beatWhen it starts

Every sound, one after another

soundNames() is the list, so a program can play them all:

function onMouseDown() {
  soundNames().forEach((name, i) => {
    playSound(name, { after: i * 0.7 })
  })
}

A sound of your own

The ready-made sounds are short tunes on small synths. When you want one that is not there, make it the same way: a synth with a quick shape, and a note or two. This is a laser that falls:

const zapper = makeSynth({ wave: "square", attack: 0, decay: 0.2, sustain: 0, pitchSweep: 24, pitchSweepDecay: 0.15 })

function onMouseDown() {
  zapper.play("C5", 0.2)
}

pitchSweep begins each note that many semitones off and lets it fall into place. See Synths and their settings.