Game guide

Music that reacts to your game.

AlgoWASM gives a game endless music that follows the action. This guide shows complete set-ups for LittleJS and three.js. The same five steps work in any engine.

Set-up

Install the package:

npm install @algo-wasm/algo-wasm

The engine needs two files to be served by your site. Copy them from the package into the folder your game serves static files from, usually public/:

cp node_modules/@algo-wasm/algo-wasm/dist/algo_wasm.wasm public/
cp node_modules/@algo-wasm/algo-wasm/dist/worklet/algo-worklet.js public/

The pattern

  1. Create one player when the game loads. If your engine already has an AudioContext, pass it in so music and sound effects share one.
  2. Start on the first input. Browsers block audio until the player clicks, taps, or presses a key.
  3. Feed it game state. Map danger, speed, or progress to setEnergy() and setIntensity(). Send a value only when it has changed, not on every frame.
  4. Listen for beats. Use beat, bar, and section-change events to time visuals and gameplay.
  5. Pause and clean up. Call pause() with the game, and destroy() when the game is torn down. destroy() frees the engine's memory.

Events arrive in small batches about every 21 ms, so a handler can run slightly after the sound. That is fine for flashes and camera kicks. For anything that must be sample-exact, use the sample field each event carries.

LittleJS

LittleJS creates its own AudioContext and exports it as audioContext. Passing it to AlgoWASM keeps one context for the whole game. LittleJS allows gameInit to be asynchronous, so the engine can load there. This example was written against LittleJS 1.30.

import {
  audioContext,
  drawRect,
  engineInit,
  hsl,
  keyWasPressed,
  mouseWasPressed,
  vec2
} from 'littlejsengine';
import { AlgoWasmPlayer, builtInProfiles } from '@algo-wasm/algo-wasm';

let music;
let musicStarted = false;
let beatPulse = 0;
let danger = 0;
let sentEnergy = -1;

async function gameInit() {
  music = await AlgoWasmPlayer.create({
    wasmUrl: '/algo_wasm.wasm',
    workletUrl: '/algo-worklet.js',
    // Share the context LittleJS made. The player will not close a context
    // it did not create.
    audioContext,
    profile: builtInProfiles.dubstep(),
    // Use a different seed per level and each level gets its own song.
    seed: 1995n
  });

  music.on('beat', () => {
    beatPulse = 1;
  });
  music.on('error', error => console.error(error));
}

function gameUpdate() {
  // Audio may only start after the player's first click or key press.
  if (music && !musicStarted && (mouseWasPressed(0) || keyWasPressed('Space'))) {
    musicStarted = true;
    music.start();
  }

  // Replace this with your own measure of how tense the game is, from 0 to 1.
  danger = Math.min(1, danger + 0.0005);

  // Send energy only when it has moved, not sixty times a second.
  if (music && Math.abs(danger - sentEnergy) > 0.02) {
    sentEnergy = danger;
    music.setEnergy(danger);
    music.setIntensity(0.4 + danger * 0.6);
  }

  beatPulse *= 0.9;
}

function gameRender() {
  // A square that kicks on every beat.
  const size = 2 + beatPulse;
  drawRect(vec2(0, 0), vec2(size, size), hsl(0.48, 0.8, 0.5 + beatPulse * 0.3));
}

engineInit(gameInit, gameUpdate, () => {}, gameRender, () => {});

Good to know

three.js

If your scene already uses a THREE.AudioListener for sound effects, pass its context to AlgoWASM so both share one AudioContext. If it does not, leave audioContext out and the player creates its own. This example was written against three.js r187.

import * as THREE from 'three';
import { AlgoWasmPlayer, builtInProfiles } from '@algo-wasm/algo-wasm';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.append(renderer.domElement);

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);
camera.position.z = 4;

const listener = new THREE.AudioListener();
camera.add(listener);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(),
  new THREE.MeshNormalMaterial()
);
scene.add(cube);

const music = await AlgoWasmPlayer.create({
  wasmUrl: '/algo_wasm.wasm',
  workletUrl: '/algo-worklet.js',
  audioContext: listener.context,
  profile: builtInProfiles.amigaHouse95ish(),
  seed: 42n
});

let beatPulse = 0;
music.on('beat', () => {
  beatPulse = 1;
});
music.on('section-change', event => {
  // A new section is a good moment to change the lighting or the camera.
  scene.background = new THREE.Color(event.section === 'drop' ? 0x1b1035 : 0x0b0e13);
});
music.on('error', error => console.error(error));

// Audio may only start after a click, tap, or key press.
let musicStarted = false;
addEventListener(
  'pointerdown',
  () => {
    musicStarted = true;
    music.start();
  },
  { once: true }
);

renderer.setAnimationLoop(() => {
  beatPulse *= 0.9;
  cube.scale.setScalar(1 + beatPulse * 0.35);
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
});

// Stop the music while the tab is hidden, and carry on when it returns.
document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    music.pause();
  } else if (musicStarted) {
    music.resume();
  }
});

Good to know

Recipes

You want Do this
A different song for each level music.setSeed(levelNumber). The same level always gets the same song.
A different style for each world music.setProfile(builtInProfiles.dubDeepHouse())
Calm menus, tense boss fights music.setMood('calm') or music.setMood('tense')
Drums drop out when the player hides music.setMuted('kick', true), and the same for snare.
Only the bass during a cutscene music.setSolo('bass', true)
A music volume slider music.setVolume(value) with a value from 0 to 1.
Spawn enemies on the bar line music.on('bar', spawnWave)
A pre-rendered clip for a trailer await music.renderOffline({ seconds: 30 }) returns the samples without playing them.

Track names are kick, snare, closed_hat, open_hat, percussion, bass, chords, pad, lead, arp, and fx. The full API is in the API reference.

Licence

AlgoWASM is released under the AGPL-3.0-or-later licence. A game that uses it and is distributed, or offered over a network, must make its complete source code available under the same licence. Check that this suits your project before you ship.

Shipped something with it?

Star the repository so other game developers can find it, and open an issue to show us what you made.

Star AlgoWASM on GitHub