Skip to content

Getting started ​

This page takes you from an install to one sound that gets muffled by a wall.

Requirements ​

  • A browser with Web Audio. Earshot has no runtime dependencies and works with any engine that can give it an audio context.
  • For the mic: HTTPS or localhost. An iframe also needs allow="microphone".

Using debuff? Go to Earshot with debuff, where walls come from your tilemap.

Install ​

bash
npm i @debuffjp/earshot

Create a listener ​

The listener is the player's ears. pos is read on every update, in your world units, and tile says how many world units make one tile.

ts
import { createListener, wallsOnGrid } from "@debuffjp/earshot";

const ctx = new AudioContext(); // Resume it from a tap or key press.

const tiles = [
  [null, null, "solid", null, null],
  [null, null, "solid", null, null],
];

const ear = createListener(ctx, {
  tile: 16,
  pos: () => player,
  world: {
    wallsBetween: (a, b) => wallsOnGrid(tiles, a, b),
  },
});

Inside wallsBetween, points are already in tiles. tiles[y][x] holds a material name or nothing.

Add a source ​

A source is any AudioNode. This one is a looping buffer you've already decoded:

ts
const node = new AudioBufferSourceNode(ctx, { buffer: radioBuffer, loop: true });
const radio = ear.source(node, { pos: () => radioPosition });
node.start();

A source stays silent until the first update(), so call ear.update() right after adding a sound you want heard at once.

Update from your game loop ​

ts
// 10 to 20 times a second is enough.
ear.update();

radio.state; // "audible" | "out-of-range" | "muted"
radio.mix?.cutoff; // 1200 behind one solid wall

Move the player to the other side of the wall and the radio gets duller and quieter. radio.mix holds the numbers behind what you hear, so you can show them on screen or test them.

Clean up ​

radio.remove() disconnects one source and leaves its input node usable. ear.dispose() removes every source and the reverbs.

Next ​

  • Sound: walls, materials, reverbs and tuning.
  • Loudness: the mic as game input.
  • Voice: voice chat and rooms.
  • API: every export.