From 6cf9c4bfec64dba70a77b46b0e0a048625d6c201 Mon Sep 17 00:00:00 2001
From: Maxi <223365242+maximilianfeix@users.noreply.github.com>
Date: Sun, 15 Nov 2026 10:12:16 +0100
Subject: [PATCH] Player: voice handle, cooldown, voice cap, loops, mute
play() now returns a voice { stop(fade?), rate(r), node } instead of the bare
source node (stop() keeps working). Per-sound guards: cooldown (default 30 ms,
compared by start time so delay-spread plays still happen) and voices (default
4, oldest stopped with a fade). loop option; loop: true on a Sound renders a
seamless loop (tail crossfaded into the head) and play() loops it by default.
muted(on?) keeps the volume for unmute; not stored (README one-liner).
Four loop sounds: rain-loop, wind-loop (nature), engine-idle, force-field
(world). sounds.test checks every take at 44.1/48 kHz for a click-free wrap and
an even level; play.test covers the player with a fake AudioContext.
Gallery: loop sounds toggle on click. Player 3.08 kB gzip (limit 3.1 kB,
was 2.9); sizes and counts updated in READMEs, skill, gallery, brand.
---
CHANGELOG.md | 18 ++
README.md | 53 +++--
README.zh-CN.md | 18 +-
brand/BRAND.md | 2 +-
brand/banners/social-preview.svg | 2 +-
brand/make_brand.py | 2 +-
e2e/gallery.spec.ts | 14 +-
gallery/index.html | 4 +-
gallery/main.ts | 38 +++-
library/catalog.gen.json | 320 +++++++++++++++++++++++++++++++
library/nature.ts | 28 ++-
library/world.ts | 26 +++
package.json | 8 +-
scripts/bake.ts | 1 +
scripts/build.ts | 2 +-
skills/plinkfx/SKILL.md | 10 +-
skills/plinkfx/reference.md | 29 +++
src/core/index.ts | 4 +-
src/core/play.ts | 108 +++++++----
src/core/synth.ts | 13 +-
src/core/types.ts | 6 +
src/core/wav.ts | 24 +--
src/index.ts | 4 +-
src/sounds.gen.ts | 12 ++
tests/hashes.json | 24 +++
tests/play.test.ts | 220 +++++++++++++++++++++
tests/sounds.test.ts | 24 ++-
27 files changed, 914 insertions(+), 100 deletions(-)
create mode 100644 tests/play.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 78dbedd..b04390f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,23 @@
# Changelog
+## Unreleased
+
+**A protective player, and loops.**
+
+- `play()` returns a voice: `stop(fade?)` fades out (10 ms by default, so no click), `rate(r)` glides the
+ playback rate, `node` is the `AudioBufferSourceNode`. Code that called `.stop()` on the old return value
+ keeps working. Still `undefined` when a sound is skipped.
+- `cooldown` (default 0.03 s): the same sound started again within it is skipped, so 30 coin pickups in
+ one frame are one coin. `0` turns it off; plays spread out with `delay` are compared by start time.
+- `voices` (default 4): at most this many copies of a sound at once; one more stops the oldest with a fade.
+- `loop` option, and `loop: true` on a Sound renders it as a seamless loop (the tail crossfaded into the
+ head, every take tested for a click-free wrap and an even level). Four loop sounds: `rain-loop`,
+ `wind-loop`, `engine-idle`, `force-field`. Loop sounds loop by default and are exempt from the cooldown.
+- `muted(on?)`: mute everything and keep the volume. Not stored; the README has the `localStorage` one-liner.
+- `stopAll()` fades in 10 ms instead of cutting.
+- Gallery: loop sounds start on click and stop on the next click; hover and arrow keys don't start them.
+- Player: 3.1 kB gzip (was 2.9), everything 15.6 kB. 184 sounds.
+
## 0.2.0 (2026-11-12)
**180 sounds in 15 categories** (was 163 in 13).
diff --git a/README.md b/README.md
index f5620dd..922b4fd 100644
--- a/README.md
+++ b/README.md
@@ -3,13 +3,13 @@
-**180 game sound effects, written as code.** Coins, jumps, hits, lasers, explosions,
-UI clicks and the rest of what a game needs, each one a few readable numbers that a 2.9 kB player turns into sound.
+**184 game sound effects, written as code.** Coins, jumps, hits, lasers, explosions,
+UI clicks and the rest of what a game needs, each one a few readable numbers that a 3.1 kB player turns into sound.
CC0, no audio files, no account.
-**[▶ Hear all 180 in your browser](https://maximilianfeix.github.io/plinkfx/)** (one click per sound, tweak any of them and share the link) · [play the 30-second demo game](https://maximilianfeix.github.io/plinkfx/game.html) · [watch the 30 s video with sound](https://github.com/maximilianfeix/plinkfx/blob/main/docs/media/hero-16x9.mp4)
+**[▶ Hear all 184 in your browser](https://maximilianfeix.github.io/plinkfx/)** (one click per sound, tweak any of them and share the link) · [play the 30-second demo game](https://maximilianfeix.github.io/plinkfx/game.html) · [watch the 30 s video with sound](https://github.com/maximilianfeix/plinkfx/blob/main/docs/media/hero-16x9.mp4)
```bash
npm i plinkfx
@@ -27,17 +27,48 @@ sound like a loop.
More ways to play: options, game setup, tree-shaking, your own sound
-**By name** (every sound included, 14.9 kB gzipped):
+**By name** (every sound included, 15.6 kB gzipped):
```js
-import { play, volume } from "plinkfx";
+import { play, volume, muted } from "plinkfx";
play("laser");
play("coin", { volume: 0.5, rate: 1.2 }); // quieter, a bit higher
play("step-wood", { variant: 2 }); // a specific take (0-3)
play("step-wood", { pan: -0.6 }); // to the left
play("coin", { delay: 0.1 }); // 100 ms later
-volume(0.8); // master volume, 0 mutes
+volume(0.8); // master volume, 0..1
+muted(true); // mute everything, muted() reads it
+```
+
+**The player protects your mix.** The same sound started again within 30 ms is skipped (`cooldown`),
+so 30 coin pickups in one frame make one coin, not one deafening stack. At most 4 copies of a sound
+play at once (`voices`); one more stops the oldest with a short fade. Both are per call:
+
+```js
+play("step-grass", { cooldown: 0.08 }); // footsteps: at most one every 80 ms
+play("explosion", { voices: 2 }); // keep the mix clear
+play("click", { cooldown: 0, voices: 16 }); // off
+```
+
+**Loops**: `rain-loop`, `wind-loop`, `engine-idle` and `force-field` are seamless and loop until you stop
+them. `play()` returns a voice you can stop (with a fade) or bend:
+
+```js
+const engine = play("engine-idle");
+engine?.rate(1.6); // revs up, gliding
+engine?.stop(0.5); // fade out over 0.5 s
+play("coin", { loop: true }); // any sound can loop; loop: false plays a loop sound once
+```
+
+`play()` returns `undefined` when it skips a sound (on the server, inside the cooldown, before the first
+click), hence the `?.`. The voice's `node` is the `AudioBufferSourceNode` if you need more.
+
+`muted()` is not saved. To remember it, one line at startup and one where you toggle it:
+
+```js
+muted(localStorage.muted == "1");
+localStorage.muted = muted(!muted()) ? "1" : "0";
```
**In a game:** browsers keep audio locked until the first click or key press. `unlockAudio()` resumes
@@ -57,7 +88,7 @@ stopAll();
Everything is safe to import on the server (Next.js, Nuxt, SvelteKit): `play()` and `volume()` do
nothing there.
-**Only what you use** (player plus one sound: 2.8 kB gzipped). Importing anything from `"plinkfx"`
+**Only what you use** (player plus one sound: 3 kB gzipped). Importing anything from `"plinkfx"`
includes every sound, so use the subpaths when size matters:
```js
@@ -125,9 +156,9 @@ const useSfx = (name) => useCallback((opts) => play(name, opts), [name]);
| Alerts | 10 | `alarm` `warning` `low-health` `heartbeat` `countdown` `radar-ping` |
| Jingles | 9 | `victory` `checkpoint` `level-complete` `game-over` `secret-found` `achievement` |
| Doors & mechanics | 10 | `door-open` `door-heavy` `lock-open` `chest-open` `lever` `ratchet` |
-| World | 11 | `whoosh` `swing` `splash` `water-drop` `bubble` `wind` `glass-break` |
+| World | 13 | `whoosh` `swing` `splash` `water-drop` `wind` `glass-break` `engine-idle` (loop) `force-field` (loop) |
| Creatures | 9 | `bat-flap` `slime-blob` `growl-small` `ghost-moan` `bee-buzz` `voice-babble` |
-| Nature | 6 | `thunder-far` `rain-drop` `bird-chirp` `frog-croak` `leaf-rustle` `stone-drop` |
+| Nature | 8 | `thunder-far` `rain-drop` `bird-chirp` `frog-croak` `stone-drop` `rain-loop` (loop) `wind-loop` (loop) |
Every sound with a one-line description: `npx plinkfx list`, or the [gallery](https://maximilianfeix.github.io/plinkfx/).
@@ -237,9 +268,9 @@ sfxr (DrPetter, 2007) started this genre, and these are the tools most people re
| | **plinkfx** | [ZzFX](https://github.com/KilledByAPixel/ZzFX) | [jsfxr](https://github.com/chr15m/jsfxr) | [Kenney audio packs](https://kenney.nl/assets/category:Audio) |
|---|---|---|---|---|
| What it is | named sound library as code | tiny synth + designer | sfxr port: generator + library | WAV/OGG asset packs |
-| Size (gzip) | 2.9 kB player, 14.9 kB with all sounds | ~1.3 kB | ~6.3 kB | no code, files |
+| Size (gzip) | 3.1 kB player, 15.6 kB with all sounds | ~1.3 kB | ~6.3 kB | no code, files |
| Licence | CC0 sounds, MIT code | MIT | Unlicense | CC0 |
-| Named sounds | 180 | 4 examples, random generators | random generators per category | many, generic file names |
+| Named sounds | 184 | 4 examples, random generators | random generators per category | many, generic file names |
| Matched loudness | yes, measured in tests | no | no | not stated |
| Same input, same samples | yes, seeded and hash-tested | only with randomness set to 0 | per saved parameter set | fixed files |
| Variations | 4 seeded takes per sound | edit or randomise | mutate | separate files |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 4a8251b..7ec9991 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -5,7 +5,7 @@
# plinkfx
-**180 个游戏音效,全部用代码写成。** 金币、跳跃、打击、激光、爆炸、UI 点击……每个音效只是几个看得懂的参数,由 2.9 kB 的播放器在浏览器里实时合成。音效 CC0,可商用,无需署名;没有音频文件,无需注册。
+**184 个游戏音效,全部用代码写成。** 金币、跳跃、打击、激光、爆炸、UI 点击……每个音效只是几个看得懂的参数,由 3.1 kB 的播放器在浏览器里实时合成。音效 CC0,可商用,无需署名;没有音频文件,无需注册。
@@ -23,7 +23,7 @@ play("coin");
每个音效有 4 个变体,每次播放都会换一个和上次不同的,第一百个金币也不会听起来像在循环。
-只打包用到的音效(播放器 + 一个音效约 2.8 kB gzip):
+只打包用到的音效(播放器 + 一个音效约 3 kB gzip):
```js
import { play } from "plinkfx/core";
@@ -33,6 +33,16 @@ play(coin);
play(jump, { volume: 0.5 });
```
+播放器会保护你的混音:同一个音效 30 ms 内重复触发会被跳过(`cooldown`),同一个音效最多同时播放 4 个(`voices`),再多就淡出最早的那个。
+`rain-loop`、`wind-loop`、`engine-idle`、`force-field` 是无缝循环音效,会一直播放到你停止它:
+
+```js
+const engine = play("engine-idle");
+engine?.rate(1.6); // 平滑升速
+engine?.stop(0.5); // 0.5 秒淡出
+muted(true); // 全部静音;不会自动保存,需要时自己存进 localStorage
+```
+
## 包含哪些音效
@@ -50,9 +60,9 @@ play(jump, { volume: 0.5 });
| 提示 | 10 | `alarm` `warning` `low-health` `countdown` |
| 短旋律 | 9 | `victory` `level-complete` `game-over` `achievement` |
| 门与机关 | 10 | `door-open` `door-heavy` `chest-open` `lever` |
-| 环境 | 11 | `whoosh` `splash` `water-drop` `wind` `glass-break` |
+| 环境 | 13 | `whoosh` `splash` `water-drop` `wind` `glass-break` `engine-idle`(循环) |
| 生物 | 9 | `bat-flap` `slime-blob` `growl-small` `ghost-moan` `voice-babble` |
-| 自然 | 6 | `thunder-far` `rain-drop` `bird-chirp` `frog-croak` `stone-drop` |
+| 自然 | 8 | `thunder-far` `rain-drop` `bird-chirp` `stone-drop` `rain-loop`(循环) |
## 导出给游戏引擎
diff --git a/brand/BRAND.md b/brand/BRAND.md
index 5cb4a54..a3b9844 100644
--- a/brand/BRAND.md
+++ b/brand/BRAND.md
@@ -122,7 +122,7 @@ Why monospace and why the system's own:
everywhere: in the gallery, the README and the terminal. One typeface for both keeps them in one voice.
- Measurements line up. Loudness, peaks and durations in the gallery and in `plinkfx measure` read as columns.
- No font download. The gallery promises that nothing loads except the page; a web font would break that and
- cost more than the whole 2.9 kB player.
+ cost more than the whole 3.1 kB player.
Sizes in the gallery: 15 px base with 1.5 line height. Weights: regular for text, 600 or 700 for headings and
labels. Emphasis is weight or plink-text, not italics.
diff --git a/brand/banners/social-preview.svg b/brand/banners/social-preview.svg
index a0c5582..6ca99e8 100644
--- a/brand/banners/social-preview.svg
+++ b/brand/banners/social-preview.svg
@@ -1 +1 @@
-
+
diff --git a/brand/make_brand.py b/brand/make_brand.py
index 141c2f8..e229248 100644
--- a/brand/make_brand.py
+++ b/brand/make_brand.py
@@ -171,7 +171,7 @@ def main():
png("favicon/favicon.svg", "favicon/apple-touch-icon.png", 180, 180)
# social preview, X header, README banners
count = len(json.load(open(os.path.join(HERE, "..", "library", "catalog.gen.json")))["sounds"])
- write("banners/social-preview.svg", card(1280, 640, "game sound effects as code", f"{count} sounds · CC0 · 2.9 kB player · no audio files"))
+ write("banners/social-preview.svg", card(1280, 640, "game sound effects as code", f"{count} sounds · CC0 · 3.1 kB player · no audio files"))
png("banners/social-preview.svg", "banners/social-preview.png", 1280, 640)
write("banners/x-header.svg", card(1500, 500, "game sound effects as code", "", scale=0.85))
png("banners/x-header.svg", "banners/x-header.png", 1500, 500)
diff --git a/e2e/gallery.spec.ts b/e2e/gallery.spec.ts
index b73d232..c5d25e9 100644
--- a/e2e/gallery.spec.ts
+++ b/e2e/gallery.spec.ts
@@ -20,10 +20,22 @@ test("gallery lists every sound and plays one on click", async ({ page }) => {
await expect(page).toHaveURL(/#coin$/);
});
+test("loop sounds start on click and stop on the next", async ({ page }) => {
+ await page.goto("./");
+ const tile = page.locator('.tile[data-name="rain-loop"]');
+ await tile.click();
+ await expect(tile).toHaveClass(/playing/);
+ await expect(page.locator("#p-name")).toHaveText("rain-loop");
+ await page.waitForTimeout(400);
+ await expect(tile).toHaveClass(/playing/);
+ await tile.click();
+ await expect(tile).not.toHaveClass(/playing/);
+});
+
test("the lede reads cleanly (no leftover template text)", async ({ page }) => {
await page.goto("./");
const lede = await page.locator(".lede").innerText();
- expect(lede).toMatch(/^\d+ sounds in \d+ categories, CC0, a 2\.9\skB player, no audio files\.$/);
+ expect(lede).toMatch(/^\d+ sounds in \d+ categories, CC0, a 3\.1\skB player, no audio files\.$/);
});
test("search and category filter", async ({ page }) => {
diff --git a/gallery/index.html b/gallery/index.html
index 90712c2..8503e50 100644
--- a/gallery/index.html
+++ b/gallery/index.html
@@ -4,7 +4,7 @@
plinkfx · game sound effects as code
-
+
@@ -37,7 +37,7 @@
Game sound effects as code.
-
sounds in categories, CC0, a 2.9 kB player, no audio files.
+
sounds in categories, CC0, a 3.1 kB player, no audio files.
npm i plinkfx
diff --git a/gallery/main.ts b/gallery/main.ts
index ef540d8..86d954a 100644
--- a/gallery/main.ts
+++ b/gallery/main.ts
@@ -74,7 +74,21 @@ const editCache = () => {
};
// ---------- audio + playheads ----------
-const playing = new Map();
+const playing = new Map();
+// Loop sounds (rain-loop, engine-idle, ...) run until clicked again.
+const loops = new Map();
+function stopLoop(name: string) {
+ const src = loops.get(name);
+ if (!src) return false;
+ src.stop();
+ loops.delete(name);
+ playing.delete(name);
+ for (const el of viewsOf(name)) el.classList.remove("playing"), drawView(el, -1);
+ if (name == current.name) $(".panel").classList.remove("playing");
+ return true;
+}
+/** A click: plays a one-shot, starts a loop sound, or stops it when it is already running. */
+const toggleItem = (it: Item, take?: number) => stopLoop(it.name) || playItem(it, take);
let raf = 0;
// Everything on the page that shows this sound: its grid tile and, for the favourites, its pad.
const viewsOf = (name: string) => document.querySelectorAll(`.tile[data-name="${name}"], .pad[data-pad="${name}"]`);
@@ -88,11 +102,15 @@ function playItem(it: Item, take = it == current ? seed : undefined, sound = it
}
const v = take ?? Math.floor(Math.random() * 4),
b = buffer(sound, v),
- src = ctx.createBufferSource();
+ src = ctx.createBufferSource(),
+ loop = !!it.loop;
+ // A tweak or another take restarts a running loop.
+ if (loop) stopLoop(it.name), loops.set(it.name, src);
src.buffer = b;
+ src.loop = loop;
src.connect(ctx.destination);
src.start();
- playing.set(it.name, { start: ctx.currentTime, dur: b.duration });
+ playing.set(it.name, { start: ctx.currentTime, dur: b.duration, loop });
for (const el of viewsOf(it.name)) {
// restart the press flash even when the same sound is retriggered
el.classList.remove("playing");
@@ -117,7 +135,7 @@ function caption(name: string) {
function tick() {
const now = context().currentTime;
for (const [name, p] of playing) {
- const k = Math.min((now - p.start) / p.dur, 1),
+ const k = p.loop ? ((now - p.start) / p.dur) % 1 : Math.min((now - p.start) / p.dur, 1),
views = viewsOf(name);
for (const el of views) drawView(el, k < 1 ? k : -1);
if (name == current.name) drawWave($("#wave"), waveOf(edited(), seed, 180), k < 1 ? k : -1);
@@ -455,7 +473,7 @@ function init() {
greeted = true;
const it = byName.get(p.dataset.pad!)!;
select(it);
- playItem(it);
+ toggleItem(it);
});
let hoverTimer = 0;
@@ -466,7 +484,7 @@ function init() {
hoverTimer = window.setTimeout(() => {
const it = byName.get(t.dataset.name!)!;
select(it);
- playItem(it, 0);
+ if (!it.loop) playItem(it, 0);
}, 110);
});
grid.addEventListener("pointerout", () => clearTimeout(hoverTimer));
@@ -476,7 +494,7 @@ function init() {
greeted = true;
const it = byName.get(t.dataset.name!)!;
select(it);
- playItem(it);
+ toggleItem(it);
});
grid.addEventListener("keydown", (e) => {
const t = (e.target as HTMLElement).closest(".tile");
@@ -490,7 +508,7 @@ function init() {
next.focus();
const it = byName.get(next.dataset.name!)!;
select(it);
- playItem(it, 0);
+ if (!it.loop) playItem(it, 0);
});
panel.addEventListener("click", (e) => {
@@ -503,7 +521,7 @@ function init() {
} else if (b.dataset.tab) {
tab = b.dataset.tab as typeof tab;
renderPanel();
- } else if (b.id == "p-play") playItem(current, seed);
+ } else if (b.id == "p-play") toggleItem(current, seed);
else if (b.id == "p-roll") roll();
else if (b.id == "p-reset") {
knobs = { ...NEUTRAL };
@@ -562,7 +580,7 @@ function init() {
playItem(current, seed);
} else if (e.key == "c") copy($("#p-code").textContent!, $("#p-copy"));
else if (e.key == "d") download();
- else if (e.key == "p") playItem(current, seed);
+ else if (e.key == "p") toggleItem(current, seed);
}
});
addEventListener("hashchange", () => {
diff --git a/library/catalog.gen.json b/library/catalog.gen.json
index e35d829..08f972d 100644
--- a/library/catalog.gen.json
+++ b/library/catalog.gen.json
@@ -12228,6 +12228,166 @@
}
]
},
+ {
+ "name": "engine-idle",
+ "id": "engineIdle",
+ "cat": "world",
+ "desc": "Engine idling, seamless loop (play with rate for revs)",
+ "gain": 0.347,
+ "limited": false,
+ "loop": true,
+ "m": {
+ "peak": -5.62,
+ "truePeak": -5.62,
+ "lufsMax": -16.87,
+ "duration": 3,
+ "centroid": 273
+ },
+ "env": [
+ 1,
+ 0.99,
+ 0.96,
+ 0.98,
+ 0.91,
+ 0.89,
+ 0.92,
+ 0.94,
+ 0.93,
+ 0.95,
+ 0.89,
+ 0.94,
+ 0.91,
+ 0.92,
+ 0.91,
+ 0.93,
+ 0.91,
+ 0.94,
+ 0.94,
+ 0.91,
+ 0.89,
+ 0.93,
+ 0.93,
+ 0.94,
+ 0.94,
+ 0.93,
+ 0.94,
+ 0.92,
+ 0.96,
+ 0.95,
+ 0.93,
+ 0.91,
+ 0.9,
+ 0.94,
+ 0.92,
+ 0.92,
+ 0.91,
+ 0.9,
+ 0.91,
+ 0.89
+ ],
+ "takes": [
+ {
+ "lufsMax": -16.87,
+ "truePeak": -5.62,
+ "duration": 3
+ },
+ {
+ "lufsMax": -17.57,
+ "truePeak": -6.15,
+ "duration": 3
+ },
+ {
+ "lufsMax": -16.12,
+ "truePeak": -4.46,
+ "duration": 3
+ },
+ {
+ "lufsMax": -17.47,
+ "truePeak": -6.33,
+ "duration": 3
+ }
+ ]
+ },
+ {
+ "name": "force-field",
+ "id": "forceField",
+ "cat": "world",
+ "desc": "Force field or reactor hum, seamless loop",
+ "gain": 0.234,
+ "limited": false,
+ "loop": true,
+ "m": {
+ "peak": -8.15,
+ "truePeak": -8.15,
+ "lufsMax": -16.85,
+ "duration": 3,
+ "centroid": 458
+ },
+ "env": [
+ 0.99,
+ 1,
+ 0.99,
+ 0.95,
+ 0.91,
+ 0.9,
+ 0.9,
+ 0.9,
+ 0.91,
+ 0.92,
+ 0.91,
+ 0.92,
+ 0.93,
+ 0.93,
+ 0.93,
+ 0.92,
+ 0.91,
+ 0.91,
+ 0.91,
+ 0.9,
+ 0.9,
+ 0.91,
+ 0.91,
+ 0.91,
+ 0.91,
+ 0.92,
+ 0.93,
+ 0.92,
+ 0.92,
+ 0.91,
+ 0.91,
+ 0.91,
+ 0.9,
+ 0.9,
+ 0.9,
+ 0.91,
+ 0.91,
+ 0.91,
+ 0.92,
+ 0.93
+ ],
+ "takes": [
+ {
+ "lufsMax": -16.85,
+ "truePeak": -8.15,
+ "duration": 3
+ },
+ {
+ "lufsMax": -17.5,
+ "truePeak": -8.76,
+ "duration": 3
+ },
+ {
+ "lufsMax": -16.18,
+ "truePeak": -7.59,
+ "duration": 3
+ },
+ {
+ "lufsMax": -17.44,
+ "truePeak": -8.64,
+ "duration": 3
+ }
+ ]
+ },
{
"name": "whoosh",
"id": "whoosh",
@@ -13808,6 +13968,166 @@
}
]
},
+ {
+ "name": "rain-loop",
+ "id": "rainLoop",
+ "cat": "nature",
+ "desc": "Steady rain, seamless loop",
+ "gain": 0.53,
+ "limited": false,
+ "loop": true,
+ "m": {
+ "peak": -8.04,
+ "truePeak": -8,
+ "lufsMax": -18.02,
+ "duration": 3,
+ "centroid": 4989
+ },
+ "env": [
+ 0.87,
+ 0.88,
+ 0.95,
+ 0.87,
+ 0.91,
+ 0.88,
+ 0.91,
+ 1,
+ 0.89,
+ 0.94,
+ 0.98,
+ 0.99,
+ 0.93,
+ 0.9,
+ 0.94,
+ 0.93,
+ 0.94,
+ 0.97,
+ 0.95,
+ 0.92,
+ 0.91,
+ 0.94,
+ 0.96,
+ 0.93,
+ 0.91,
+ 0.93,
+ 0.89,
+ 0.89,
+ 0.91,
+ 0.95,
+ 0.96,
+ 0.94,
+ 0.94,
+ 0.94,
+ 0.89,
+ 0.88,
+ 0.96,
+ 0.9,
+ 0.93,
+ 0.89
+ ],
+ "takes": [
+ {
+ "lufsMax": -18.02,
+ "truePeak": -8,
+ "duration": 3
+ },
+ {
+ "lufsMax": -18.11,
+ "truePeak": -8.02,
+ "duration": 3
+ },
+ {
+ "lufsMax": -18.01,
+ "truePeak": -7.98,
+ "duration": 3
+ },
+ {
+ "lufsMax": -17.87,
+ "truePeak": -7.26,
+ "duration": 3
+ }
+ ]
+ },
+ {
+ "name": "wind-loop",
+ "id": "windLoop",
+ "cat": "nature",
+ "desc": "Wind blowing with slow gusts, seamless loop",
+ "gain": 0.913,
+ "limited": false,
+ "loop": true,
+ "m": {
+ "peak": -5.11,
+ "truePeak": -5.08,
+ "lufsMax": -17.99,
+ "duration": 3,
+ "centroid": 1773
+ },
+ "env": [
+ 0.79,
+ 0.76,
+ 0.82,
+ 0.89,
+ 0.8,
+ 0.81,
+ 0.85,
+ 0.85,
+ 0.88,
+ 0.83,
+ 0.94,
+ 0.88,
+ 0.86,
+ 0.8,
+ 0.88,
+ 0.86,
+ 0.86,
+ 0.83,
+ 0.91,
+ 1,
+ 0.79,
+ 0.8,
+ 0.92,
+ 0.86,
+ 0.85,
+ 0.9,
+ 0.78,
+ 0.83,
+ 0.86,
+ 0.89,
+ 0.85,
+ 0.83,
+ 0.9,
+ 0.9,
+ 0.84,
+ 0.86,
+ 0.96,
+ 0.86,
+ 0.86,
+ 0.91
+ ],
+ "takes": [
+ {
+ "lufsMax": -17.99,
+ "truePeak": -5.08,
+ "duration": 3
+ },
+ {
+ "lufsMax": -18.17,
+ "truePeak": -6.05,
+ "duration": 3
+ },
+ {
+ "lufsMax": -18.03,
+ "truePeak": -5.75,
+ "duration": 3
+ },
+ {
+ "lufsMax": -17.81,
+ "truePeak": -5.55,
+ "duration": 3
+ }
+ ]
+ },
{
"name": "thunder-far",
"id": "thunderFar",
diff --git a/library/nature.ts b/library/nature.ts
index e54579a..778435d 100644
--- a/library/nature.ts
+++ b/library/nature.ts
@@ -1,7 +1,33 @@
import { def } from "./def.ts";
-// One-shots from outdoors. No loops: these are events (a drop, a croak, a far rumble).
+// Sounds from outdoors: events (a drop, a croak, a far rumble) and two seamless ambience loops.
+// Loops: every layer spans the whole render (d: 0 keeps every take the same length); see Sound.loop.
export default def("nature", {
+ "rain-loop": ["Steady rain, seamless loop", {
+ loop: true,
+ vary: 0.6,
+ varyF: 2,
+ layers: [
+ { wave: "pink", hp: 500, lp: 7000, a: 0.02, h: 3.48, d: 0, gain: 0.7 },
+ { wave: "noise", bp: 4200, q: 0.7, a: 0.02, h: 3.48, d: 0, gain: 0.22 },
+ { wave: "brown", lp: 350, a: 0.02, h: 3.48, d: 0, gain: 0.35 },
+ // Close drops: short ticks scattered over the loop.
+ ...[0.07, 0.31, 0.46, 0.62, 0.9, 1.13, 1.27, 1.55, 1.71, 1.98, 2.2, 2.36, 2.61, 2.83, 3.05].map((at, i) => ({ wave: "noise" as const, bp: 2600 + (i % 4) * 600, q: 1.5, at, a: 0.001, d: 0.012, shape: -5, gain: 0.55 + (i % 3) * 0.15 })),
+ ],
+ }],
+ "wind-loop": ["Wind blowing with slow gusts, seamless loop", {
+ loop: true,
+ vary: 0.5,
+ varyF: 2,
+ layers: [
+ { wave: "pink", bp: 520, q: 1.2, a: 0.02, h: 3.48, d: 0, gain: 0.8 },
+ { wave: "brown", lp: 220, a: 0.02, h: 3.48, d: 0, gain: 0.45 },
+ // Gusts: band sweeps that swell and fall inside the loop.
+ { wave: "pink", bp: 600, bpTo: 1400, q: 2.5, at: 0.15, a: 0.9, d: 1, shape: 1.5, gain: 0.7 },
+ { wave: "pink", bp: 1300, bpTo: 650, q: 2.5, at: 1.6, a: 0.7, d: 1.1, shape: 1.5, gain: 0.6 },
+ { wave: "noise", bp: 2300, bpTo: 2900, q: 7, at: 0.5, a: 1, d: 1.2, shape: 2, gain: 0.1 },
+ ],
+ }],
"thunder-far": ["Distant thunder rolling in", {
vary: 0.5,
varyF: 3,
diff --git a/library/world.ts b/library/world.ts
index 60c430d..2edd716 100644
--- a/library/world.ts
+++ b/library/world.ts
@@ -1,6 +1,32 @@
import { def } from "./def.ts";
export default def("world", {
+ // Loops: every layer spans the whole render (d: 0 keeps every take the same length); see Sound.loop.
+ "engine-idle": ["Engine idling, seamless loop (play with rate for revs)", {
+ loop: true,
+ // No pitch spread: whole cycles in the 3 s loop keep the crossfade in phase.
+ vary: 0,
+ varyF: 1.5,
+ varyG: 0.8,
+ layers: [
+ { wave: "square", freq: 31, duty: 0.3, lp: 240, drive: 1.5, vib: [2, 0.25], a: 0.02, h: 3.48, d: 0 },
+ { wave: "saw", freq: 62, lp: 420, vib: [2, 0.25], a: 0.02, h: 3.48, d: 0, gain: 0.45 },
+ { wave: "crunch", freq: 124, lp: 1400, hp: 300, a: 0.02, h: 3.48, d: 0, gain: 0.12 },
+ { wave: "brown", lp: 160, a: 0.02, h: 3.48, d: 0, gain: 0.5 },
+ ],
+ }],
+ "force-field": ["Force field or reactor hum, seamless loop", {
+ loop: true,
+ vary: 0,
+ varyF: 1.5,
+ varyG: 0.8,
+ layers: [
+ { wave: "sine", freq: 60, drive: 0.6, a: 0.02, h: 3.48, d: 0 },
+ { wave: "saw", freq: 120, lp: 900, vib: [1, 0.04], a: 0.02, h: 3.48, d: 0, gain: 0.3 },
+ { wave: "triangle", freq: 180, vib: [3, 0.03], a: 0.02, h: 3.48, d: 0, gain: 0.25 },
+ { wave: "noise", bp: 3200, q: 3, a: 0.02, h: 3.48, d: 0, gain: 0.05 },
+ ],
+ }],
whoosh: ["Medium whoosh for dashes and swings", {
varyF: 3,
varyG: 1.5,
diff --git a/package.json b/package.json
index 5af529b..1c2ebf2 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "plinkfx",
"version": "0.2.0",
- "description": "Game sound effects as code: 180 CC0 SFX (coin, jump, laser, UI clicks) and a 2.9 kB Web Audio player. CLI for WAV/OGG, no audio files.",
+ "description": "Game sound effects as code: 184 CC0 SFX (coin, jump, laser, UI clicks, loops) and a 3.1 kB Web Audio player. CLI for WAV/OGG, no audio files.",
"keywords": [
"sound-effects",
"sfx",
@@ -86,7 +86,7 @@
"name": "player: render + play + wav",
"path": "dist/core.js",
"import": "{ play, render, wav }",
- "limit": "3 kB",
+ "limit": "3.1 kB",
"gzip": true
},
{
@@ -95,14 +95,14 @@
"dist/core.js": "{ play }",
"dist/sounds.js": "{ coin }"
},
- "limit": "3 kB",
+ "limit": "3.1 kB",
"gzip": true
},
{
"name": "everything: all sounds, play by name",
"path": "dist/index.js",
"import": "*",
- "limit": "15.5 kB",
+ "limit": "16 kB",
"gzip": true
}
],
diff --git a/scripts/bake.ts b/scripts/bake.ts
index 6351883..e23544e 100644
--- a/scripts/bake.ts
+++ b/scripts/bake.ts
@@ -93,6 +93,7 @@ for (const e of library) {
desc: e.desc,
gain,
limited: capped,
+ ...(e.sound.loop && { loop: true }),
m: { peak: r2(m.peak), truePeak: r2(m.truePeak), lufsMax: r2(m.lufsMax), duration: r2(m.duration), centroid: Math.round(m.centroid) },
// 40-bar peak envelope of take 0 for the gallery tiles (so the page renders no audio at load).
env: envelope(render(sound, { sampleRate: SR }), 40),
diff --git a/scripts/build.ts b/scripts/build.ts
index 2eeca62..e0cb082 100644
--- a/scripts/build.ts
+++ b/scripts/build.ts
@@ -34,7 +34,7 @@ chmodSync("dist/cli.js", 0o755);
const cat = JSON.parse(readFileSync("library/catalog.gen.json", "utf8"));
writeFileSync(
"dist/catalog.json",
- JSON.stringify({ categories: cat.categories, sounds: cat.sounds.map((s: any) => ({ name: s.name, cat: s.cat, desc: s.desc, duration: s.m.duration, lufs: s.m.lufsMax })) }),
+ JSON.stringify({ categories: cat.categories, sounds: cat.sounds.map((s: any) => ({ name: s.name, cat: s.cat, desc: s.desc, duration: s.m.duration, lufs: s.m.lufsMax, ...(s.loop && { loop: true }) })) }),
);
execFileSync(process.platform == "win32" ? "npx.cmd" : "npx", ["tsc", "-p", "tsconfig.build.json"], { stdio: "inherit", shell: process.platform == "win32" });
console.log("built dist/");
diff --git a/skills/plinkfx/SKILL.md b/skills/plinkfx/SKILL.md
index fe8aa92..5d7c80f 100644
--- a/skills/plinkfx/SKILL.md
+++ b/skills/plinkfx/SKILL.md
@@ -6,7 +6,7 @@ description: Design, render and measure game sound effects as code with plinkfx.
# plinkfx: sound effects as code
plinkfx sounds are small JSON objects (layers of oscillators or noise with envelopes, pitch sweeps,
-filters and a few effects) that a 2.9 kB player renders in the browser, and the `plinkfx` CLI renders
+filters and a few effects) that a 3.1 kB player renders in the browser, and the `plinkfx` CLI renders
to WAV. You design a sound by writing that object, rendering it, measuring it, and adjusting.
**You cannot hear.** Say so once. Your checks are numbers and spectrograms; the user's ears decide.
@@ -22,7 +22,7 @@ Everything below uses `npx plinkfx`. Inside the plinkfx repo itself use `node di
## 1. Start from the catalogue
-180 sounds in 15 categories already exist and are tuned. Reuse before you invent.
+184 sounds in 15 categories already exist and are tuned (four of them seamless loops). Reuse before you invent.
```bash
npx plinkfx list # all sounds: name, category, description
@@ -94,6 +94,9 @@ import door from "./sounds/door.json" with { type: "json" };
play(door);
```
+`play()` skips a repeat of the same sound within 30 ms (`cooldown`) and keeps at most 4 copies playing
+(`voices`); both are options. It returns a voice (`stop(fade)`, `rate(r)`) or `undefined` when skipped.
+
5. one sentence: "I can't hear it: please listen and tell me what to change (darker, shorter, more punch...)."
For files for an engine: `npx plinkfx export assets/sfx --format both` writes every catalogue sound as
@@ -104,4 +107,5 @@ for short sounds and leave Force To Mono off (the files are mono already; it can
- Don't copy presets or samples from other tools or packs unless their licence allows it.
- Don't claim a sound "sounds great". Report the numbers and let the user listen.
-- Don't exceed -1 dBTP or ship sounds longer than about 4 s; those are loops or music, not effects.
+- Don't exceed -1 dBTP or ship one-shots longer than about 4 s. Ambience and engines are loops: see
+ "Loops" in reference.md.
diff --git a/skills/plinkfx/reference.md b/skills/plinkfx/reference.md
index 6a3d73c..5c2149b 100644
--- a/skills/plinkfx/reference.md
+++ b/skills/plinkfx/reference.md
@@ -42,6 +42,35 @@ Times in seconds, frequencies in Hz. Everything is optional except `layers`.
| `varyG` | `0` | Level spread per layer between takes, dB. Footsteps 2, hits 1.5. |
| `limit` | set by bake | Look-ahead peak limiter. The catalogue bake turns it on for short, spiky sounds when it gains loudness without clipping. |
| `gain` | set by bake | Output level. In your own sounds, use it to keep the true peak under -1 dBTP. |
+| `loop` | `true` | Render a seamless loop instead of a one-shot (see below). `play()` loops it until `stop()`. |
+
+## Loops
+
+With `loop: true` the renderer cuts the last 0.5 s of the sound and crossfades the first 0.25 s of that
+cut into the start, so the last sample runs straight into the first: no click, no gap. Rules:
+
+- Every layer holds for the whole sound: short `a` (0.02), long `h`, and `d: 0` (no release; it also
+ keeps every take the same length). A 3.5 s render gives a 3.0 s loop.
+- Events inside the loop (rain drops, gusts) are normal layers with `at`.
+- Tonal loops: `vary: 0` and whole-number frequencies and vibrato rates (cycles that fit the 3 s loop
+ exactly) keep the crossfade in phase. Vary the takes with `varyF` and a small `varyG` instead.
+- Noise loops can keep `vary`; the crossfade is close to equal power for them.
+
+Catalogue loops: `rain-loop`, `wind-loop` (nature), `engine-idle`, `force-field` (world). The tests check
+every take at 44.1 and 48 kHz: the wrap step is smaller than the sound's 99.9th-percentile step and the
+level across the wrap stays within 3 dB.
+
+## Playing
+
+`play(sound, options)` returns a voice `{ stop(fade?), rate(r), node }`, or `undefined` when it skipped the
+sound. Options: `variant`, `volume`, `rate`, `pan`, `delay`, `loop`, plus two guards:
+
+| Option | Default | What it does |
+|---|---|---|
+| `cooldown` | 0.03 | Skip the play when the same sound starts within this many seconds. 0 = off. Loops are exempt. |
+| `voices` | 4 | Most copies of one sound at once; one more stops the oldest, with a short fade. |
+
+`muted(true | false)` mutes everything and keeps the volume; `muted()` reads it. It is not stored.
## Recipes
diff --git a/src/core/index.ts b/src/core/index.ts
index 38cd3d2..40dd4b6 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -1,5 +1,5 @@
export { render, rng } from "./synth.ts";
-export { play, buffer, context, volume, preload, stopAll, unlockAudio, VARIANTS } from "./play.ts";
-export type { PlayOptions } from "./play.ts";
+export { play, buffer, context, volume, muted, preload, stopAll, unlockAudio, VARIANTS } from "./play.ts";
+export type { PlayOptions, Voice } from "./play.ts";
export { wav } from "./wav.ts";
export type { Sound, Layer, Wave, RenderOptions } from "./types.ts";
diff --git a/src/core/play.ts b/src/core/play.ts
index 8656c94..8b1fd89 100644
--- a/src/core/play.ts
+++ b/src/core/play.ts
@@ -12,6 +12,25 @@ export interface PlayOptions {
pan?: number;
/** Start after this many seconds. Default 0. */
delay?: number;
+ /**
+ * Skip this play when the same sound already starts within this many seconds of it, so 30 coin
+ * pickups in one frame make one coin, not one loud stack. Default 0.03. 0 turns it off. Loops are exempt.
+ */
+ cooldown?: number;
+ /** Most copies of this sound playing at once; one more stops the oldest (with a short fade). Default 4. */
+ voices?: number;
+ /** Repeat until `stop()`. Default: true for loop sounds (`rain-loop`, `engine-idle`, ...), false otherwise. */
+ loop?: boolean;
+}
+
+/** A sound that is playing, returned by play(). */
+export interface Voice {
+ /** Stop it, fading out over `fade` seconds. Default 0.01 (just enough to avoid a click). */
+ stop(fade?: number): void;
+ /** Glide to a new playback rate (an engine revving, a charge-up rising). */
+ rate(r: number): void;
+ /** The underlying AudioBufferSourceNode. */
+ node: AudioBufferSourceNode;
}
/** Every sound ships with this many takes (seeds 0..3). */
@@ -19,10 +38,12 @@ export const VARIANTS = 4;
let ctx: AudioContext | undefined,
master: GainNode | undefined,
- level = 1;
-const cache = new WeakMap(),
- last = new WeakMap(),
- live = new Set(),
+ level = 1,
+ off = false;
+// Per sound: rendered takes, last take, last start time, voices playing.
+const seen = new WeakMap(),
+ state = (s: Sound) => seen.get(s) || seen.set(s, { b: [], v: (Math.random() * VARIANTS) | 0, t: -9, on: [] }).get(s)!,
+ live = new Set(),
ok = () => typeof AudioContext != "undefined";
/** The shared AudioContext, created on first use. Connect your own nodes to it if you like. */
@@ -30,7 +51,7 @@ export function context(): AudioContext {
if (!ctx) {
ctx = new AudioContext();
master = ctx.createGain();
- master.gain.value = level;
+ volume(level);
// Soft safety limiter, so ten coins at once don't clip.
const k = ctx.createDynamicsCompressor();
k.threshold.value = -3;
@@ -45,7 +66,16 @@ export function context(): AudioContext {
/** Master volume, 0..1 (0 mutes). Safe to call before any sound played, and on the server. */
export function volume(v: number) {
level = Math.max(0, Number.isFinite(v) ? v : 1);
- if (master) master.gain.value = level;
+ if (master) master.gain.value = off ? 0 : level;
+}
+
+/**
+ * Mute or unmute everything (the volume is kept for unmute). Returns the current state; muted() just reads it.
+ * Not stored: to remember it, `muted(localStorage.muted == "1")` at startup and save it when it changes.
+ */
+export function muted(on?: boolean): boolean {
+ if (on != null) (off = on), volume(level);
+ return off;
}
/**
@@ -69,13 +99,10 @@ const EVENTS = ["pointerdown", "keydown", "touchend"];
/** Render (once) and return the AudioBuffer for one take of a sound. */
export function buffer(sound: Sound, variant = 0): AudioBuffer {
const c = context(),
- list = cache.get(sound) || [];
- cache.set(sound, list);
+ list = state(sound).b;
if (!list[variant]) {
- const data = render(sound, { sampleRate: c.sampleRate, seed: variant }),
- b = c.createBuffer(1, data.length, c.sampleRate);
- b.getChannelData(0).set(data);
- list[variant] = b;
+ const data = render(sound, { sampleRate: c.sampleRate, seed: variant });
+ (list[variant] = c.createBuffer(1, data.length, c.sampleRate)).getChannelData(0).set(data);
}
return list[variant];
}
@@ -99,45 +126,54 @@ export function preload(sounds: Sound[], takes = VARIANTS): Promise {
}
/**
- * Play a sound. Returns the source node (to stop it early), or undefined when nothing can play:
- * on the server, or while audio is still locked and no user gesture is happening (so sounds
- * triggered before the first click don't all fire at once when audio unlocks).
+ * Play a sound. Returns a Voice (to stop it or change its rate), or undefined when it was skipped:
+ * on the server, inside the cooldown, or while audio is still locked and no user gesture is happening
+ * (so sounds triggered before the first click don't all fire at once when audio unlocks).
*/
-export function play(sound: Sound, o: PlayOptions = {}): AudioBufferSourceNode | undefined {
+export function play(sound: Sound, o: PlayOptions = {}): Voice | undefined {
if (!ok()) return;
const c = context();
- if (c.state != "running") {
- c.resume();
- const ua = (navigator as any).userActivation;
- if (ua && !ua.isActive) return;
- }
- let v = o.variant;
- if (v == null) {
- const l = last.get(sound) ?? -1;
- v = Math.floor(Math.random() * (l < 0 ? VARIANTS : VARIANTS - 1));
- if (l >= 0 && v >= l) v++;
- }
- last.set(sound, v);
+ if (c.state != "running" && (c.resume(), (navigator as any).userActivation?.isActive == false)) return;
+ const at = c.currentTime + Math.max(0, o.delay || 0),
+ loop = o.loop ?? !!sound.loop,
+ s = state(sound);
+ if (!loop && Math.abs(at - s.t) < (o.cooldown ?? 0.03)) return;
+ s.t = at;
+ // A random take, never the same one twice in a row.
+ const v = (s.v = o.variant ?? (s.v + 1 + ((Math.random() * (VARIANTS - 1)) | 0)) % VARIANTS);
+ while (s.on.length >= (o.voices || 4)) s.on[0].stop();
const src = c.createBufferSource(),
- g = c.createGain();
+ g = c.createGain(),
+ drop = () => (live.delete(h), s.on.splice(s.on.indexOf(h) >>> 0, 1)),
+ h: Voice = {
+ node: src,
+ stop(f = 0.01) {
+ const t = c.currentTime;
+ g.gain.setTargetAtTime(0, t, f / 5 + 1e-3);
+ src.stop(t + f + 0.01);
+ drop();
+ },
+ rate: (r) => src.playbackRate.setTargetAtTime(r, c.currentTime, 0.02),
+ };
let node: AudioNode = src.connect(g);
src.buffer = buffer(sound, v);
+ src.loop = loop;
src.playbackRate.value = o.rate ?? 1;
g.gain.value = o.volume ?? 1;
if (o.pan) {
const p = c.createStereoPanner();
- p.pan.value = Math.max(-1, Math.min(1, o.pan));
+ p.pan.value = o.pan; // the param clamps to -1..1 itself
node = node.connect(p);
}
node.connect(master!);
- live.add(src);
- src.onended = () => live.delete(src);
- src.start(c.currentTime + Math.max(0, o.delay || 0));
- return src;
+ live.add(h);
+ s.on.push(h);
+ src.onended = drop;
+ src.start(at);
+ return h;
}
/** Stop every sound that is playing. */
export function stopAll() {
- for (const s of live) s.stop();
- live.clear();
+ for (const h of live) h.stop(0);
}
diff --git a/src/core/synth.ts b/src/core/synth.ts
index ca7e5a1..0e7dcba 100644
--- a/src/core/synth.ts
+++ b/src/core/synth.ts
@@ -53,9 +53,8 @@ const layer = (L: Layer, out: Float32Array, sr: number, pitch: number, stretch:
n = Math.min(Math.round(len * sr), out.length - start),
q = L.q || 0.707,
filters: [(x: number, f: number) => number, number, number][] = [];
- if (L.lp) filters.push([svf(sr, q, 0), L.lp * fv, (L.lpTo || L.lp) * fv]);
- if (L.bp) filters.push([svf(sr, q, 1), L.bp * fv, (L.bpTo || L.bp) * fv]);
- if (L.hp) filters.push([svf(sr, q, 2), L.hp * fv, (L.hpTo || L.hp) * fv]);
+ // lp, bp, hp in that order; the index is the svf mode.
+ (["lp", "bp", "hp"] as const).forEach((k, m) => L[k] && filters.push([svf(sr, q, m), L[k]! * fv, (L[`${k}To`] || L[k]!) * fv]));
let phase = 0,
mod = 0,
held = 0,
@@ -257,6 +256,14 @@ export function render(sound: Sound, opts: RenderOptions = {}): Float32Array {
for (let i = x.length; i--; ) gl[i] = Math.min(0.84 / Math.max(Math.abs(x[i]), 1e-9), 1, i + 1 < x.length ? gl[i + 1] + 1 / A : 1);
for (let i = 0; i < x.length; i++) x[i] *= gl[i] = Math.min(gl[i], i ? gl[i - 1] + 1 / Rl : 1);
}
+ if (sound.loop) {
+ // Seamless loop of length L: crossfade the 0.25 s after it into its start, so sample L-1
+ // runs on into sample 0; the attack is faded out under that and the release past it is cut.
+ const X = Math.round(sr / 4),
+ L = Math.round(end * sr) - 2 * X;
+ for (let i = 0; i < X; i++) x[i] = x[i] * (i / X) ** 0.75 + x[i + L] * (1 - i / X) ** 0.75;
+ return x.slice(0, L);
+ }
x = x.slice(0, last + 1);
const fade = Math.min(Math.round(sr * 0.005), x.length);
for (let i = 0; i < fade; i++) x[x.length - 1 - i] *= i / fade;
diff --git a/src/core/types.ts b/src/core/types.ts
index 6ffbd3c..494d841 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -109,6 +109,12 @@ export interface Sound {
limit?: number;
/** Sample-rate reduction in Hz (sample and hold), e.g. 8000. */
rate?: number;
+ /**
+ * Render a seamless loop instead of a one-shot: the last 0.5 s are cut (0.25 s of them crossfaded into the
+ * start), so the buffer wraps without a click. Give every layer a long hold (`h`), a short attack and a
+ * release (`d`) under 0.25 s. play() loops these by default.
+ */
+ loop?: boolean;
}
export interface RenderOptions {
diff --git a/src/core/wav.ts b/src/core/wav.ts
index e674062..09a7611 100644
--- a/src/core/wav.ts
+++ b/src/core/wav.ts
@@ -1,20 +1,12 @@
/** Encode mono samples as a 16-bit PCM WAV file. */
export function wav(samples: Float32Array, sampleRate = 44100): Uint8Array {
const n = samples.length,
- b = new DataView(new ArrayBuffer(44 + n * 2)),
- str = (o: number, s: string) => [...s].forEach((c, i) => b.setUint8(o + i, c.charCodeAt(0)));
- str(0, "RIFF");
- b.setUint32(4, 36 + n * 2, true);
- str(8, "WAVEfmt ");
- b.setUint32(16, 16, true);
- b.setUint16(20, 1, true);
- b.setUint16(22, 1, true);
- b.setUint32(24, sampleRate, true);
- b.setUint32(28, sampleRate * 2, true);
- b.setUint16(32, 2, true);
- b.setUint16(34, 16, true);
- str(36, "data");
- b.setUint32(40, n * 2, true);
- for (let i = 0; i < n; i++) b.setInt16(44 + i * 2, Math.round(Math.max(-1, Math.min(1, samples[i])) * 32767), true);
- return new Uint8Array(b.buffer);
+ b = new ArrayBuffer(44 + n * 2),
+ pcm = new Int16Array(b, 44);
+ // Typed arrays use the platform's byte order, which is little-endian everywhere JS runs, as WAV wants.
+ // The 44-byte header as 32-bit words: "RIFF", size, "WAVE", "fmt ", 16, PCM + mono,
+ // sample rate, byte rate, block align + 16 bits, "data", data size.
+ new Uint32Array(b, 0, 11).set([0x46464952, 36 + n * 2, 0x45564157, 0x20746d66, 16, 0x10001, sampleRate, sampleRate * 2, 0x100002, 0x61746164, n * 2]);
+ for (let i = 0; i < n; i++) pcm[i] = Math.round(Math.max(-1, Math.min(1, samples[i])) * 32767);
+ return new Uint8Array(b);
}
diff --git a/src/index.ts b/src/index.ts
index 859e127..33b62dc 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -14,8 +14,8 @@ import type { PlayOptions, RenderOptions, Sound } from "./core/index.ts";
import type { Name } from "./sounds.gen.ts";
export * from "./sounds.gen.ts";
-export { context, volume, wav, rng, stopAll, unlockAudio, VARIANTS } from "./core/index.ts";
-export type { Sound, Layer, Wave, RenderOptions, PlayOptions } from "./core/index.ts";
+export { context, volume, muted, wav, rng, stopAll, unlockAudio, VARIANTS } from "./core/index.ts";
+export type { Sound, Layer, Wave, RenderOptions, PlayOptions, Voice } from "./core/index.ts";
const library = sounds as unknown as Record;
diff --git a/src/sounds.gen.ts b/src/sounds.gen.ts
index 9ae0eac..b796a46 100644
--- a/src/sounds.gen.ts
+++ b/src/sounds.gen.ts
@@ -310,6 +310,10 @@ export const button: Sound = {"varyF":1.5,"varyG":1,"layers":[{"wave":"noise","b
export const ratchet: Sound = {"layers":[{"wave":"noise","bp":3200,"q":3,"at":0,"a":0.001,"d":0.02,"shape":3,"drive":1},{"wave":"metal","freq":1500,"hp":4000,"at":0,"a":0.001,"d":0.012,"gain":0.3},{"wave":"noise","bp":2400,"q":3,"at":0.045,"a":0.001,"d":0.02,"shape":3,"drive":1},{"wave":"metal","freq":1500,"hp":4000,"at":0.045,"a":0.001,"d":0.012,"gain":0.3},{"wave":"noise","bp":3200,"q":3,"at":0.09,"a":0.001,"d":0.02,"shape":3,"drive":1},{"wave":"metal","freq":1500,"hp":4000,"at":0.09,"a":0.001,"d":0.012,"gain":0.3},{"wave":"noise","bp":2400,"q":3,"at":0.135,"a":0.001,"d":0.02,"shape":3,"drive":1},{"wave":"metal","freq":1500,"hp":4000,"at":0.135,"a":0.001,"d":0.012,"gain":0.3},{"wave":"noise","bp":3200,"q":3,"at":0.18,"a":0.001,"d":0.02,"shape":3,"drive":1},{"wave":"metal","freq":1500,"hp":4000,"at":0.18,"a":0.001,"d":0.012,"gain":0.3},{"wave":"noise","bp":2400,"q":3,"at":0.225,"a":0.001,"d":0.02,"shape":3,"drive":1},{"wave":"metal","freq":1500,"hp":4000,"at":0.225,"a":0.001,"d":0.012,"gain":0.3},{"wave":"noise","bp":3200,"q":3,"at":0.27,"a":0.001,"d":0.02,"shape":3,"drive":1},{"wave":"metal","freq":1500,"hp":4000,"at":0.27,"a":0.001,"d":0.012,"gain":0.3}],"gain":1.04};
/** Machine starts up and hums */
export const machine: Sound = {"vary":0.2,"layers":[{"wave":"saw","freq":30,"to":110,"curve":0.6,"lp":600,"a":0.2,"h":0.6,"d":0.3,"shape":2},{"wave":"pink","bp":900,"bpTo":1600,"q":1.5,"a":0.3,"h":0.5,"d":0.3,"gain":0.2},{"wave":"noise","bp":2000,"a":0.3,"h":0.5,"d":0.3,"gain":0.08}],"gain":0.376};
+/** Engine idling, seamless loop (play with rate for revs) */
+export const engineIdle: Sound = {"loop":true,"vary":0,"varyF":1.5,"varyG":0.8,"layers":[{"wave":"square","freq":31,"duty":0.3,"lp":240,"drive":1.5,"vib":[2,0.25],"a":0.02,"h":3.48,"d":0},{"wave":"saw","freq":62,"lp":420,"vib":[2,0.25],"a":0.02,"h":3.48,"d":0,"gain":0.45},{"wave":"crunch","freq":124,"lp":1400,"hp":300,"a":0.02,"h":3.48,"d":0,"gain":0.12},{"wave":"brown","lp":160,"a":0.02,"h":3.48,"d":0,"gain":0.5}],"gain":0.347};
+/** Force field or reactor hum, seamless loop */
+export const forceField: Sound = {"loop":true,"vary":0,"varyF":1.5,"varyG":0.8,"layers":[{"wave":"sine","freq":60,"drive":0.6,"a":0.02,"h":3.48,"d":0},{"wave":"saw","freq":120,"lp":900,"vib":[1,0.04],"a":0.02,"h":3.48,"d":0,"gain":0.3},{"wave":"triangle","freq":180,"vib":[3,0.03],"a":0.02,"h":3.48,"d":0,"gain":0.25},{"wave":"noise","bp":3200,"q":3,"a":0.02,"h":3.48,"d":0,"gain":0.05}],"gain":0.234};
/** Medium whoosh for dashes and swings */
export const whoosh: Sound = {"varyF":3,"varyG":1.5,"layers":[{"wave":"pink","bp":450,"bpTo":1800,"q":1.6,"a":0.13,"d":0.02,"shape":1},{"wave":"pink","bp":1800,"bpTo":500,"q":1.6,"at":0.13,"a":0.01,"d":0.3,"shape":-4},{"wave":"noise","bp":3000,"bpTo":6000,"a":0.12,"d":0.12,"gain":0.2},{"wave":"brown","lp":300,"a":0.12,"d":0.15,"gain":0.3}],"limit":1,"gain":1.84};
/** Sword or stick swing */
@@ -350,6 +354,10 @@ export const creatureHurt: Sound = {"vary":1.5,"layers":[{"wave":"saw","freq":42
export const creatureDie: Sound = {"vary":1,"verb":[0.4,0.2],"layers":[{"wave":"saw","freq":330,"to":80,"curve":0.8,"vib":[9,0.6],"formant":[730,1090,2440],"kt":1,"a":0.01,"h":0.1,"d":0.6,"shape":-2.5,"drive":0.8}],"gain":0.57};
/** Gibberish dialogue blips, like a character talking */
export const voiceBabble: Sound = {"vary":2,"layers":[{"wave":"square","duty":0.3,"freq":280,"arp":[0,4,-2,7,2,5],"arpRate":0.07,"formant":[270,2290,3010],"a":0.005,"h":0.36,"d":0.06,"shape":-3}],"gain":0.384};
+/** Steady rain, seamless loop */
+export const rainLoop: Sound = {"loop":true,"vary":0.6,"varyF":2,"layers":[{"wave":"pink","hp":500,"lp":7000,"a":0.02,"h":3.48,"d":0,"gain":0.7},{"wave":"noise","bp":4200,"q":0.7,"a":0.02,"h":3.48,"d":0,"gain":0.22},{"wave":"brown","lp":350,"a":0.02,"h":3.48,"d":0,"gain":0.35},{"wave":"noise","bp":2600,"q":1.5,"at":0.07,"a":0.001,"d":0.012,"shape":-5,"gain":0.55},{"wave":"noise","bp":3200,"q":1.5,"at":0.31,"a":0.001,"d":0.012,"shape":-5,"gain":0.7000000000000001},{"wave":"noise","bp":3800,"q":1.5,"at":0.46,"a":0.001,"d":0.012,"shape":-5,"gain":0.8500000000000001},{"wave":"noise","bp":4400,"q":1.5,"at":0.62,"a":0.001,"d":0.012,"shape":-5,"gain":0.55},{"wave":"noise","bp":2600,"q":1.5,"at":0.9,"a":0.001,"d":0.012,"shape":-5,"gain":0.7000000000000001},{"wave":"noise","bp":3200,"q":1.5,"at":1.13,"a":0.001,"d":0.012,"shape":-5,"gain":0.8500000000000001},{"wave":"noise","bp":3800,"q":1.5,"at":1.27,"a":0.001,"d":0.012,"shape":-5,"gain":0.55},{"wave":"noise","bp":4400,"q":1.5,"at":1.55,"a":0.001,"d":0.012,"shape":-5,"gain":0.7000000000000001},{"wave":"noise","bp":2600,"q":1.5,"at":1.71,"a":0.001,"d":0.012,"shape":-5,"gain":0.8500000000000001},{"wave":"noise","bp":3200,"q":1.5,"at":1.98,"a":0.001,"d":0.012,"shape":-5,"gain":0.55},{"wave":"noise","bp":3800,"q":1.5,"at":2.2,"a":0.001,"d":0.012,"shape":-5,"gain":0.7000000000000001},{"wave":"noise","bp":4400,"q":1.5,"at":2.36,"a":0.001,"d":0.012,"shape":-5,"gain":0.8500000000000001},{"wave":"noise","bp":2600,"q":1.5,"at":2.61,"a":0.001,"d":0.012,"shape":-5,"gain":0.55},{"wave":"noise","bp":3200,"q":1.5,"at":2.83,"a":0.001,"d":0.012,"shape":-5,"gain":0.7000000000000001},{"wave":"noise","bp":3800,"q":1.5,"at":3.05,"a":0.001,"d":0.012,"shape":-5,"gain":0.8500000000000001}],"gain":0.53};
+/** Wind blowing with slow gusts, seamless loop */
+export const windLoop: Sound = {"loop":true,"vary":0.5,"varyF":2,"layers":[{"wave":"pink","bp":520,"q":1.2,"a":0.02,"h":3.48,"d":0,"gain":0.8},{"wave":"brown","lp":220,"a":0.02,"h":3.48,"d":0,"gain":0.45},{"wave":"pink","bp":600,"bpTo":1400,"q":2.5,"at":0.15,"a":0.9,"d":1,"shape":1.5,"gain":0.7},{"wave":"pink","bp":1300,"bpTo":650,"q":2.5,"at":1.6,"a":0.7,"d":1.1,"shape":1.5,"gain":0.6},{"wave":"noise","bp":2300,"bpTo":2900,"q":7,"at":0.5,"a":1,"d":1.2,"shape":2,"gain":0.1}],"gain":0.913};
/** Distant thunder rolling in */
export const thunderFar: Sound = {"vary":0.5,"varyF":3,"varyG":1.5,"verb":[0.7,0.4],"layers":[{"wave":"brown","lp":320,"lpTo":90,"a":0.25,"h":0.25,"d":1.5,"shape":-3,"gain":1.6,"drive":0.8},{"wave":"brown","lp":900,"lpTo":300,"at":0.1,"a":0.01,"d":0.35,"shape":-4,"gain":0.7},{"wave":"brown","lp":900,"lpTo":300,"at":0.22,"a":0.01,"d":0.35,"shape":-4,"gain":0.5499999999999999},{"wave":"brown","lp":900,"lpTo":300,"at":0.4,"a":0.01,"d":0.35,"shape":-4,"gain":0.39999999999999997}],"gain":0.332};
/** A raindrop on a leaf */
@@ -519,6 +527,8 @@ export type Name =
| "button"
| "ratchet"
| "machine"
+ | "engine-idle"
+ | "force-field"
| "whoosh"
| "swing"
| "dash"
@@ -539,6 +549,8 @@ export type Name =
| "creature-hurt"
| "creature-die"
| "voice-babble"
+ | "rain-loop"
+ | "wind-loop"
| "thunder-far"
| "rain-drop"
| "bird-chirp"
diff --git a/tests/hashes.json b/tests/hashes.json
index dc7820d..0c12c3f 100644
--- a/tests/hashes.json
+++ b/tests/hashes.json
@@ -923,6 +923,18 @@
"d5065f905dd5b790",
"72c66852c8dcf8b9"
],
+ "engine-idle": [
+ "e0e7f2e0a525fbba",
+ "3a676f570b33e550",
+ "67b9707a444071dd",
+ "2428758a25e7aa00"
+ ],
+ "force-field": [
+ "b2344f951e055b8d",
+ "37354685f00fbfdd",
+ "94f33d7db05af231",
+ "80732eea76dd80e9"
+ ],
"whoosh": [
"13a52f8884c7fc69",
"984127141e51d712",
@@ -1043,6 +1055,18 @@
"feec5020b80a21c7",
"3552c809959b6c28"
],
+ "rain-loop": [
+ "5b39d2f03daf8d6c",
+ "9a0bfa5e7967dee7",
+ "63da9ddb52185e31",
+ "9efe111d05889a0c"
+ ],
+ "wind-loop": [
+ "323cb039f0f23df5",
+ "0c9813483ed99d2d",
+ "afd99dcad47379cd",
+ "5ca2fd320296f43a"
+ ],
"thunder-far": [
"87c9aaab933aa8e8",
"091d5377eac50268",
diff --git a/tests/play.test.ts b/tests/play.test.ts
new file mode 100644
index 0000000..afde7d8
--- /dev/null
+++ b/tests/play.test.ts
@@ -0,0 +1,220 @@
+/**
+ * The player against a fake AudioContext: the voice handle, cooldown, the voice cap, loops,
+ * stop/stopAll and mute. The fake records what play() asks of Web Audio; time moves by hand.
+ */
+import { beforeAll, describe, expect, test } from "vitest";
+import type { Sound } from "../src/core/types.ts";
+
+class Param {
+ value = 1;
+ targets: [number, number, number][] = [];
+ setTargetAtTime(v: number, t: number, tc: number) {
+ this.targets.push([v, t, tc]);
+ }
+}
+const node = () => ({ connect: (n: any) => n });
+class Source {
+ buffer: any;
+ loop = false;
+ playbackRate = new Param();
+ onended?: () => void;
+ started?: number;
+ stopped?: number;
+ ended = false;
+ connect = (n: any) => n;
+ start(t: number) {
+ this.started = t;
+ }
+ stop(t: number) {
+ this.stopped = t;
+ }
+ // What the browser does when the buffer runs out.
+ end() {
+ this.ended = true;
+ this.onended?.();
+ }
+}
+class FakeContext {
+ static last: FakeContext;
+ state = "running";
+ currentTime = 0;
+ sampleRate = 8000;
+ destination = node();
+ sources: Source[] = [];
+ gains: { gain: Param; connect: (n: any) => any }[] = [];
+ constructor() {
+ FakeContext.last = this;
+ }
+ createGain() {
+ const g = { gain: new Param(), ...node() };
+ this.gains.push(g);
+ return g;
+ }
+ createDynamicsCompressor() {
+ return { threshold: new Param(), knee: new Param(), ratio: new Param(), release: new Param(), ...node() };
+ }
+ createStereoPanner() {
+ return { pan: new Param(), ...node() };
+ }
+ createBufferSource() {
+ const s = new Source();
+ this.sources.push(s);
+ return s;
+ }
+ createBuffer(_: number, length: number, sr: number) {
+ const d = new Float32Array(length);
+ return { duration: length / sr, length, getChannelData: () => d };
+ }
+ resume() {}
+}
+
+let P: typeof import("../src/core/play.ts"), ctx: FakeContext;
+// play() typed with the fake nodes, so tests can read what was scheduled.
+const play = (s: Sound, o?: import("../src/core/play.ts").PlayOptions) => P.play(s, o) as unknown as { stop(f?: number): void; rate(r: number): void; node: Source } | undefined;
+const blip = (): Sound => ({ layers: [{ freq: 600, d: 0.05 }] }),
+ hum = (): Sound => ({ loop: true, layers: [{ wave: "noise", a: 0.01, h: 1, d: 0 }] }),
+ // Source nodes that are playing (started, not stopped).
+ running = () => ctx.sources.filter((s) => s.stopped == null && !s.ended).length;
+
+beforeAll(async () => {
+ (globalThis as any).AudioContext = FakeContext;
+ P = await import("../src/core/play.ts");
+ P.context();
+ ctx = FakeContext.last;
+});
+
+describe("play() handle", () => {
+ test("returns a voice that stops with a short fade", () => {
+ const v = play(blip())!;
+ expect(v).toBeDefined();
+ expect(v.node).toBe(ctx.sources.at(-1));
+ ctx.currentTime = 1;
+ v.stop(0.5);
+ const gain = ctx.gains.at(-1)!.gain;
+ expect(gain.targets.at(-1)![0]).toBe(0);
+ expect(gain.targets.at(-1)![1]).toBe(1);
+ expect(v.node.stopped).toBeCloseTo(1.51, 5);
+ });
+ test("stop() without a fade still declicks (10 ms)", () => {
+ const v = play(blip())!;
+ v.stop();
+ expect(v.node.stopped! - ctx.currentTime).toBeCloseTo(0.02, 5);
+ });
+ test("rate() glides the playback rate", () => {
+ const v = play(blip(), { rate: 1.5 })!;
+ expect(v.node.playbackRate.value).toBe(1.5);
+ v.rate(2);
+ expect(v.node.playbackRate.targets.at(-1)![0]).toBe(2);
+ });
+ test("delay schedules the start", () => {
+ const v = play(blip(), { delay: 0.25 })!;
+ expect(v.node.started).toBeCloseTo(ctx.currentTime + 0.25, 5);
+ });
+});
+
+describe("cooldown", () => {
+ test("the same sound within 30 ms is skipped, later it plays", () => {
+ const s = blip();
+ ctx.currentTime = 10;
+ expect(play(s)).toBeDefined();
+ expect(play(s)).toBeUndefined();
+ ctx.currentTime = 10.02;
+ expect(play(s)).toBeUndefined();
+ ctx.currentTime = 10.04;
+ expect(play(s)).toBeDefined();
+ });
+ test("other sounds are not affected", () => {
+ ctx.currentTime = 11;
+ expect(play(blip())).toBeDefined();
+ expect(play(blip())).toBeDefined();
+ });
+ test("cooldown: 0 turns it off; a longer cooldown skips more", () => {
+ const s = blip();
+ ctx.currentTime = 12;
+ expect(play(s, { cooldown: 0 })).toBeDefined();
+ expect(play(s, { cooldown: 0 })).toBeDefined();
+ ctx.currentTime = 12.2;
+ expect(play(s, { cooldown: 0.5 })).toBeUndefined();
+ });
+ test("plays spread out with delay all happen", () => {
+ const s = blip();
+ ctx.currentTime = 13;
+ for (let i = 0; i < 3; i++) expect(play(s, { delay: i * 0.1 })).toBeDefined();
+ });
+});
+
+describe("voices", () => {
+ test("at most 4 copies of a sound; the oldest is stopped first", () => {
+ const s = blip(),
+ vs = [];
+ for (let i = 0; i < 6; i++) {
+ ctx.currentTime = 20 + i * 0.1;
+ vs.push(play(s)!);
+ }
+ expect(vs.map((v) => v.node.stopped != null)).toEqual([true, true, false, false, false, false]);
+ // The stolen voices fade out instead of cutting off.
+ expect(vs[0].node.stopped).toBeGreaterThan(20.4);
+ });
+ test("voices: 1 keeps one copy", () => {
+ const s = blip(),
+ a = play(s, { voices: 1 })!;
+ ctx.currentTime += 0.1;
+ const b = play(s, { voices: 1 })!;
+ expect(a.node.stopped).toBeDefined();
+ expect(b.node.stopped).toBeUndefined();
+ });
+ test("a voice that ended frees its slot", () => {
+ const s = blip(),
+ a = play(s, { voices: 1 })!;
+ (a.node as unknown as Source).end();
+ ctx.currentTime += 0.1;
+ play(s, { voices: 1 });
+ expect(a.node.stopped).toBeUndefined();
+ });
+});
+
+describe("loops", () => {
+ test("loop sounds loop by default, until stop()", () => {
+ const v = play(hum())!;
+ expect(v.node.loop).toBe(true);
+ expect(v.node.stopped).toBeUndefined();
+ v.stop(1);
+ expect(v.node.stopped).toBeGreaterThan(ctx.currentTime + 1);
+ });
+ test("loop: true loops any sound, loop: false plays a loop sound once", () => {
+ expect(play(blip(), { loop: true })!.node.loop).toBe(true);
+ expect(play(hum(), { loop: false })!.node.loop).toBe(false);
+ });
+ test("restarting a loop right after stopping it is not swallowed by the cooldown", () => {
+ const s = hum();
+ play(s)!.stop();
+ expect(play(s)).toBeDefined();
+ });
+ test("a loop buffer is the rendered loop (3.5 s of layers -> 1.01 s - 0.5 s here)", () => {
+ const v = play(hum())!;
+ expect(v.node.buffer.duration).toBeCloseTo(0.51, 2);
+ });
+});
+
+describe("stopAll and mute", () => {
+ test("stopAll() stops every voice", () => {
+ for (let i = 0; i < 3; i++) play(blip());
+ play(hum());
+ expect(running()).toBeGreaterThan(0);
+ P.stopAll();
+ expect(running()).toBe(0);
+ });
+ test("muted() silences the master and keeps the volume for unmute", () => {
+ const master = ctx.gains[0].gain;
+ expect(P.muted()).toBe(false);
+ P.volume(0.5);
+ expect(master.value).toBe(0.5);
+ expect(P.muted(true)).toBe(true);
+ expect(master.value).toBe(0);
+ P.volume(0.8);
+ expect(master.value).toBe(0);
+ expect(P.muted()).toBe(true);
+ P.muted(false);
+ expect(master.value).toBe(0.8);
+ });
+});
diff --git a/tests/sounds.test.ts b/tests/sounds.test.ts
index c87c58d..b494a45 100644
--- a/tests/sounds.test.ts
+++ b/tests/sounds.test.ts
@@ -71,7 +71,7 @@ describe.each(library.map((e) => [e.name, e] as const))("%s", (name, e) => {
}
});
- test("click-free edges", () => {
+ test.runIf(!sound.loop)("click-free edges", () => {
for (const x of takes) {
expect(Math.abs(x[0])).toBeLessThan(0.05);
expect(Math.abs(x[x.length - 1])).toBeLessThan(0.001);
@@ -79,6 +79,28 @@ describe.each(library.map((e) => [e.name, e] as const))("%s", (name, e) => {
}
});
+ // A loop wraps from its last sample to its first: that step must look like any other step in the
+ // sound (below its 99.9th percentile), and the level must not dip or swell across the crossfade.
+ test.runIf(!!sound.loop)("seamless loop: no click or level jump at the wrap", () => {
+ for (const sr of [SR, 48000])
+ for (let seed = 0; seed < TAKES; seed++) {
+ const x = sr == SR ? takes[seed] : render(sound, { sampleRate: sr, seed }),
+ n = x.length,
+ steps = Float32Array.from({ length: n - 1 }, (_, i) => Math.abs(x[i + 1] - x[i])).sort();
+ expect(n / sr).toBeCloseTo(3, 2);
+ expect(Math.abs(x[0] - x[n - 1]), `take ${seed} at ${sr} Hz`).toBeLessThan(steps[Math.floor(n * 0.999)]);
+ // RMS in 50 ms windows over two loops back to back: around the wrap within 3 dB of the median.
+ const W = Math.round(sr * 0.05),
+ two = new Float32Array(2 * n),
+ db: number[] = [];
+ two.set(x), two.set(x, n);
+ for (let i = 0; i + W <= two.length; i += W) db.push(10 * Math.log10(two.subarray(i, i + W).reduce((a, v) => a + v * v, 0) / W));
+ const med = [...db].sort((a, b) => a - b)[db.length >> 1],
+ w = Math.floor(n / W);
+ for (const v of db.slice(w - 2, w + 8)) expect(Math.abs(v - med), `take ${seed} at ${sr} Hz`).toBeLessThan(3);
+ }
+ });
+
test("takes are variations, not copies", () => {
expect(new Set(takes.map(hash)).size).toBe(TAKES);
});