Press It Twice: a Tested Retrigger Policy for Sound Buttons, With Restart, Overlap and Ignore Modes and a Voice Limit
DEV Community

Press It Twice: a Tested Retrigger Policy for Sound Buttons, With Restart, Overlap and Ignore Modes and a Voice Limit

Every page of soundboard buttons has to answer a question that nobody asks in the design meeting: what happens when someone presses a button again while its clip is still playing?

A horn that is two seconds long and a thumb that taps three times in one second produce three overlapping horns, or one horn that keeps restarting, or one horn and two dead taps. Each of those is a legitimate choice, and each feels different in the hand.

This post builds a small voice pool that makes the choice explicit. It supports three retrigger modes, caps the number of clips playing at once, and is written so that it can be tested in Node with fakes. No browser and no audio hardware are needed to check the logic.

Three answers to "pressed again"

  • Overlap. Start another copy and let both play. This suits short percussive sounds, where a quick double tap should sound like a double hit. It is also the mode that can get loud, because copies add up.
  • Restart. Stop the earlier copy and start again from the beginning. This suits longer clips such as a sting or a quote, where two overlapping copies sound like a smear. The button always feels responsive, and the sound never gets louder than one copy.
  • Ignore. Do nothing until the clip has finished. This suits clips that should not be interrupted, and it stops an excited double tap from cutting a joke off halfway. The cost is that a tap can feel dead, so it is the mode that most needs some visual feedback.

None of these is the right default for every clip. A good board lets the mode depend on how long the clip is, and a good pool treats the mode as a setting rather than a branch scattered through click handlers.

Why a voice limit matters too

Retrigger rules look after one button. A voice limit looks after the whole page. Without one, a user who drums on a dozen buttons can start dozens of simultaneous sources. Browsers cope, but the sum of all that audio gets harsh, and on a modest phone the extra work can cause crackles.

The usual answer is voice stealing: when a new sound needs a slot and every slot is taken, stop the oldest voice. Listeners rarely notice a clip that has been playing for a while being trimmed, and they always notice a new tap that makes no sound. So the new press wins.

The design in one paragraph

The pool does not know about the Web Audio API. It is handed a play function that starts a clip and returns a stop function. That one small seam is what makes the whole thing testable: in production play creates an AudioBufferSourceNode, and in tests it records calls into an array. The pool keeps an ordered list of active voices, oldest first, and implements the three modes and the limit on top of that list.

The code

// Retrigger policy for sound buttons: what happens when a button is pressed again
// while its clip is still playing, and when too many clips play at once.
export const MODES = ["restart", "overlap", "ignore"];

export function createVoicePool({ maxVoices = 8, mode = "overlap", now = () => 0 } = {}) {
  if (!Number.isInteger(maxVoices) || maxVoices < 1)
    throw new RangeError("maxVoices must be a whole number of at least 1");
  if (!MODES.includes(mode))
    throw new RangeError(`mode must be one of ${MODES.join(", ")}`);

  const voices = []; // oldest first: { id, clipId, stop }
  let nextId = 1;
  const log = { started: 0, stopped: 0, ignored: 0, stolen: 0 };

  function remove(voice, reason) {
    const i = voices.indexOf(voice);
    if (i === -1) return;
    voices.splice(i, 1);
    log.stopped += 1;
    if (reason === "stolen") log.stolen += 1;
    voice.stop(reason);
  }

  return {
    // start(clipId, play): play(id) must return a stop function. Returns the voice id, or null if ignored.
    start(clipId, play) {
      const same = voices.filter((v) => v.clipId === clipId);
      if (same.length && mode === "ignore") {
        log.ignored += 1;
        return null;
      }
      if (same.length && mode === "restart")
        same.forEach((v) => remove(v, "restarted"));
      while (voices.length >= maxVoices)
        remove(voices[0], "stolen"); // drop the oldest voice
      const id = nextId++;
      const voice = { id, clipId, startedAt: now(), stop: play(id) }; // play gets the id so it can report ended(id)
      voices.push(voice);
      log.started += 1;
      return id;
    },
    // Call from the clip's "ended" event.
    ended(id) {
      const v = voices.find((x) => x.id === id);
      if (v) {
        voices.splice(voices.indexOf(v), 1);
      }
    },
    stopAll() {
      [...voices].forEach((v) => remove(v, "stopAll"));
    },
    active() {
      return voices.map((v) => v.clipId);
    },
    stats() {
      return { ...log, active: voices.length };
    },
  };
}

A few details deserve a comment.

The voices array is ordered by start time, so "oldest" is always voices[0]. There is no need for timestamps to decide who gets stolen, and keeping the order implicit avoids a class of bugs where two voices start in the same millisecond.

The ended method is separate from stop. When a clip finishes by itself, the audio element or source node fires an event, and the pool only needs to forget the voice. Calling stop on a clip that has already finished is harmless in most browsers but pointless, and it would make the statistics lie. Keeping the two paths separate also means the tests can tell "stopped by the pool" from "finished naturally".

The while loop that steals voices runs until there is room, rather than stealing exactly one. If someone lowers maxVoices at runtime, or if a restart removes nothing, the loop still ends with the right number of voices. A loop is cheaper to reason about than an if that has to be right on every path.

The stats object counts starts, stops, ignored presses and steals. It costs nothing, and it answers questions like "do real users ever hit the limit" during development without attaching a debugger.

Wiring it to real audio

The pool is half of the story. Here is the browser side, which is deliberately short:

const pool = createVoicePool({ maxVoices: 8, mode: "overlap" });

function playClip(clipId, buffer, ctx) {
  return pool.start(clipId, (voiceId) => {
    const src = ctx.createBufferSource();
    src.buffer = buffer;
    src.connect(ctx.destination);
    src.onended = () => pool.ended(voiceId);
    src.start();
    return () => {
      src.onended = null;
      try { src.stop(); } catch {}
    };
  });
}

Two details matter. First, the pool hands the voice id to play, so the source can report back with ended(voiceId) when it finishes by itself. Second, a stopped source also fires ended, so the stop function clears the handler before stopping; otherwise the pool would be told about a voice it has already removed.

If you later want a per-clip mode, replace the single mode option with a function modeFor(clipId). The tests below do not need to change much, because each test already picks its mode explicitly.

Tests

The tests use Node's built-in runner, so there is nothing to install. A tiny fakePlayer records stop reasons, and each test reads them back.

import test from "node:test";
import assert from "node:assert/strict";
import { createVoicePool } from "./retrigger.mjs";

// A fake "player": records every stop reason so tests can read them back.
function fakePlayer() {
  const stops = [];
  let n = 0;
  return {
    stops,
    play: () => {
      const id = ++n;
      return (reason) => stops.push(`${id}:${reason}`);
    }
  };
}

test("overlap lets the same clip play twice at once", () => {
  const p = fakePlayer();
  const pool = createVoicePool({ mode: "overlap" });
  pool.start("horn", p.play);
  pool.start("horn", p.play);
  assert.deepEqual(pool.active(), ["horn", "horn"]);
  assert.deepEqual(p.stops, []);
});

test("restart stops the earlier copy of the same clip first", () => {
  const p = fakePlayer();
  const pool = createVoicePool({ mode: "restart" });
  pool.start("horn", p.play);
  pool.start("horn", p.play);
  assert.deepEqual(pool.active(), ["horn"]);
  assert.deepEqual(p.stops, ["1:restarted"]);
});

test("restart leaves other clips alone", () => {
  const p = fakePlayer();
  const pool = createVoicePool({ mode: "restart" });
  pool.start("horn", p.play);
  pool.start("laugh", p.play);
  pool.start("horn", p.play);
  assert.deepEqual(pool.active().sort(), ["horn", "laugh"]);
});

test("ignore drops a second press and returns null", () => {
  const p = fakePlayer();
  const pool = createVoicePool({ mode: "ignore" });
  assert.equal(typeof pool.start("horn", p.play), "number");
  assert.equal(pool.start("horn", p.play), null);
  assert.equal(pool.stats().ignored, 1);
  assert.equal(pool.stats().started, 1);
});

test("a clip that has ended can be started again in ignore mode", () => {
  const p = fakePlayer();
  const pool = createVoicePool({ mode: "ignore" });
  const id = pool.start("horn", p.play);
  pool.ended(id);
  assert.equal(typeof pool.start("horn", p.play), "number");
});

test("at the voice limit the oldest voice is stolen", () => {
  const p = fakePlayer();
  const pool = createVoicePool({ maxVoices: 2, mode: "overlap" });
  pool.start("a", p.play);
  pool.start("b", p.play);
  pool.start("c", p.play);
  assert.deepEqual(pool.active(), ["b", "c"]);
  assert.deepEqual(p.stops, ["1:stolen"]);
  assert.equal(pool.stats().stolen, 1);
});

test("ended removes a voice without calling stop", () => {
  const p = fakePlayer();
  const pool = createVoicePool();
  const id = pool.start("a", p.play);
  pool.ended(id);
  assert.deepEqual(pool.active(), []);
  assert.deepEqual(p.stops, []);
});

test("stopAll stops everything once", () => {
  const p = fakePlayer();
  const pool = createVoicePool();
  pool.start("a", p.play);
  pool.start("b", p.play);
  pool.stopAll();
  pool.stopAll();
  assert.deepEqual(p.stops, ["1:stopAll", "2:stopAll"]);
});

test("bad options are rejected", () => {
  assert.throws(() => createVoicePool({ maxVoices: 0 }), RangeError);
  assert.throws(() => createVoicePool({ mode: "loop" }), RangeError);
});

test("play receives the voice id that start returns", () => {
  const pool = createVoicePool();
  let seen;
  const id = pool.start("a", (voiceId) => {
    seen = voiceId;
    return () => {};
  });
  assert.equal(seen, id);
});

The tests describe behaviour in plain sentences. "At the voice limit the oldest voice is stolen" is a rule you could read to a designer. If a later change breaks it, the failing test name says what promise was broken.

Running them:

✔ overlap lets the same clip play twice at once (1.429451ms)
✔ restart stops the earlier copy of the same clip first (0.301385ms)
✔ restart leaves other clips alone (0.157875ms)
✔ ignore drops a second press and returns null (0.176824ms)
✔ a clip that has ended can be started again in ignore mode (0.167469ms)
✔ at the voice limit the oldest voice is stolen (0.14055ms)
✔ ended removes a voice without calling stop (0.122552ms)
✔ stopAll stops everything once (0.138825ms)
✔ bad options are rejected (0.384416ms)
✔ play receives the voice id that start returns (0.24262ms)
ℹ tests 10
ℹ suites 0
ℹ pass 10
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 65.757672

Choosing a mode for each kind of clip

The code does not decide which mode a clip should use. That is a design question, and a rough guide helps:

  • Clips under about half a second, such as clicks, pops and short hits: overlap. A double tap should sound like two hits.
  • Clips of one to three seconds, such as horns, stings and short phrases: restart. Smearing is the main risk.
  • Longer clips, such as a spoken line or a short song fragment: ignore, with a visible "playing" state so the second tap does not feel broken.

If you want real material to try this on, a list of meme sound effects has clips of all three lengths, which makes the difference between the modes easy to hear.

Things this version does not do

It does not fade a stolen voice out. A hard stop can click, so a production version should ramp the gain down over a few milliseconds before calling stop.

It does not group voices, so a long music bed and a short effect share the same limit. A project that mixes the two should keep two pools.

And it does not look at loudness, so eight loud voices are still eight loud voices; a master gain or a compressor on the output is the right tool for that.

None of these is hard to add, and none changes the shape of the pool: a seam for play, an ordered list of voices and three small rules.

Takeaways

Decide what a repeated press means and write it down as a mode, rather than letting it fall out of whatever the click handler happens to do.

Put the Web Audio API behind a play function that returns a stop function. The logic becomes testable in plain Node.

Cap simultaneous voices and steal the oldest, so a new tap always makes a sound.

Keep "ended by itself" and "stopped by the pool" as separate paths, so statistics and tests stay honest.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.