Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@

## 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.7 kB. 184 sounds.

- CLI: `plinkfx mcp`, an MCP server on stdio with five tools: `list_sounds`, `show_sound`, `render_sound`,
`measure_sound` and `check_sound`. No dependencies, no network.
- CLI: `plinkfx check <sounds|file.wav> | --all [--json]` looks for clicks at the edges, cut tails, DC offset,
Expand Down
55 changes: 43 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
<img alt="plinkfx: game sound effects as code" src="https://cdn.jsdelivr.net/gh/maximilianfeix/plinkfx@main/brand/banners/readme-light.svg" width="100%">
</picture>

**<!-- count -->180<!-- /count --> 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.
**<!-- count -->184<!-- /count --> 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.

<a href="https://maximilianfeix.github.io/plinkfx/"><img src="https://cdn.jsdelivr.net/gh/maximilianfeix/plinkfx@main/docs/media/gallery.gif" alt="The plinkfx gallery: clicking tiles plays coin, jump, laser, explosion and more; each tile shows its waveform" width="100%"></a>

**[▶ Hear all <!-- count -->180<!-- /count --> 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 <!-- count -->184<!-- /count --> 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
Expand All @@ -27,17 +27,48 @@ sound like a loop.
<details>
<summary>More ways to play: options, game setup, tree-shaking, your own sound</summary>

**By name** (every sound included, 14.9 kB gzipped):
**By name** (every sound included, 15.7 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
Expand All @@ -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
Expand Down Expand Up @@ -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) |
<!-- /catalog -->

Every sound with a one-line description: `npx plinkfx list`, or the [gallery](https://maximilianfeix.github.io/plinkfx/).
Expand Down Expand Up @@ -156,7 +187,7 @@ Each sound in the gallery also has a "download .wav" button. Ready-made players

### One audio sprite (Phaser, Howler)

For the web, one file with every sound means one request instead of 180:
For the web, one file with every sound means one request instead of 184:

```bash
npx plinkfx export public/sfx --sprite --format both # all sounds, 0.1 s of silence between them
Expand Down Expand Up @@ -282,9 +313,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.7 kB with all sounds | ~1.3 kB | ~6.3 kB | no code, files |
| Licence | CC0 sounds, MIT code | MIT | Unlicense | CC0 |
| Named sounds | <!-- count -->180<!-- /count --> | 4 examples, random generators | random generators per category | many, generic file names |
| Named sounds | <!-- count -->184<!-- /count --> | 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 |
Expand Down
18 changes: 14 additions & 4 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

# plinkfx

**<!-- count -->180<!-- /count --> 个游戏音效,全部用代码写成。** 金币、跳跃、打击、激光、爆炸、UI 点击……每个音效只是几个看得懂的参数,由 2.9 kB 的播放器在浏览器里实时合成。音效 CC0,可商用,无需署名;没有音频文件,无需注册。
**<!-- count -->184<!-- /count --> 个游戏音效,全部用代码写成。** 金币、跳跃、打击、激光、爆炸、UI 点击……每个音效只是几个看得懂的参数,由 3.1 kB 的播放器在浏览器里实时合成。音效 CC0,可商用,无需署名;没有音频文件,无需注册。

<a href="https://maximilianfeix.github.io/plinkfx/"><img src="https://cdn.jsdelivr.net/gh/maximilianfeix/plinkfx@main/docs/media/gallery.gif" alt="plinkfx 在线音效库:点击方块即可试听 coin、jump、laser、explosion 等音效,每个方块显示波形" width="100%"></a>

Expand All @@ -23,7 +23,7 @@ play("coin");

每个音效有 4 个变体,每次播放都会换一个和上次不同的,第一百个金币也不会听起来像在循环。

只打包用到的音效(播放器 + 一个音效约 2.8 kB gzip):
只打包用到的音效(播放器 + 一个音效约 3 kB gzip):

```js
import { play } from "plinkfx/core";
Expand All @@ -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
```

## 包含哪些音效

<!-- catalog -->
Expand All @@ -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`(循环) |
<!-- /catalog -->

## 导出给游戏引擎
Expand Down
2 changes: 1 addition & 1 deletion brand/BRAND.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion brand/banners/social-preview.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion brand/make_brand.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 13 additions & 1 deletion e2e/gallery.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down
4 changes: 2 additions & 2 deletions gallery/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>plinkfx · game sound effects as code</title>
<meta name="description" content="%TOTAL% game sound effects made from code. Play them all, tweak them, copy one line or download the WAV. CC0, no account, a 2.9 kB player." />
<meta name="description" content="%TOTAL% game sound effects made from code. Play them all, tweak them, copy one line or download the WAV. CC0, no account, a 3.1 kB player." />
<meta name="color-scheme" content="light dark" />
<meta name="theme-color" content="#F2EDE3" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#16130F" media="(prefers-color-scheme: dark)" />
Expand Down Expand Up @@ -37,7 +37,7 @@
<div class="hero">
<div class="intro">
<h1>Game sound effects as code.</h1>
<p class="lede"><b id="total"><!--total--></b> sounds in <b id="cats-n"><!--cats--></b> categories, <b>CC0</b>, a 2.9&nbsp;kB player, no audio files.</p>
<p class="lede"><b id="total"><!--total--></b> sounds in <b id="cats-n"><!--cats--></b> categories, <b>CC0</b>, a 3.1&nbsp;kB player, no audio files.</p>
<div class="install"><code>npm i plinkfx</code><button id="install-copy" type="button">copy</button></div>
<div class="cta">
<button id="tour" type="button" class="tour">▶ Play the tour <small>10 s</small></button>
Expand Down
38 changes: 28 additions & 10 deletions gallery/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,21 @@ const editCache = () => {
};

// ---------- audio + playheads ----------
const playing = new Map<string, { start: number; dur: number }>();
const playing = new Map<string, { start: number; dur: number; loop?: boolean }>();
// Loop sounds (rain-loop, engine-idle, ...) run until clicked again.
const loops = new Map<string, AudioBufferSourceNode>();
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<HTMLElement>(`.tile[data-name="${name}"], .pad[data-pad="${name}"]`);
Expand All @@ -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");
Expand All @@ -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($<HTMLCanvasElement>("#wave"), waveOf(edited(), seed, 180), k < 1 ? k : -1);
Expand Down Expand Up @@ -455,7 +473,7 @@ function init() {
greeted = true;
const it = byName.get(p.dataset.pad!)!;
select(it);
playItem(it);
toggleItem(it);
});

let hoverTimer = 0;
Expand All @@ -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));
Expand All @@ -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<HTMLElement>(".tile");
Expand All @@ -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) => {
Expand All @@ -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 };
Expand Down Expand Up @@ -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", () => {
Expand Down
Loading
Loading