uppercut-sound-effect-synth 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .DS_Store
8
+ uv.lock
9
+ .env*
10
+ *.pem
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-sound-effect-synth
3
+ Version: 0.1.0
4
+ Summary: Deterministic procedural sound effects: envelopes, filtered noise, sweeps, seeded variation and WAV output.
5
+ Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-sound-effect-synth
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ Keywords: deterministic,procedural-audio,sound-effects,synthesis,wav
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Sound Synthesis
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: numpy>=1.24
16
+ Description-Content-Type: text/markdown
17
+
18
+ # uppercut-sound-effect-synth
19
+
20
+ Procedural sound effects that render the same way every time. It provides envelopes, band-limited noise, zero-phase and sweeping filters, pitch sweeps, soft saturation, a seeded random source, 8/16/24-bit WAV writing, thirteen ready-made sounds (whoosh, riser, impact, click, ding and more) and a pack renderer that writes a manifest of SHA-256 hashes. The same seed, sound name and take give identical samples and an identical WAV file on the same NumPy version and platform. The only dependency is NumPy.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pip install uppercut-sound-effect-synth
26
+ ```
27
+
28
+ ## Example
29
+
30
+ ```python
31
+ from uppercut_sound_effect_synth import render, write_wav, render_pack
32
+
33
+ audio = render("impact", seed=7) # (n, 2) float array, peak -3 dBFS
34
+ write_wav("impact.wav", audio) # returns the file's SHA-256
35
+
36
+ render_pack("sfx", ["whoosh", "click"], seed=7, bits=16) # also writes sfx/manifest.json
37
+ ```
38
+
39
+ Your own recipe is a function `(rng, rate) -> 1-D array`:
40
+
41
+ ```python
42
+ from uppercut_sound_effect_synth import render, tone, envelope
43
+
44
+ beep = {"beep": lambda rng, rate: tone(1000, rate // 5, rate) * envelope(rate // 5, 0.002, 2.0, rate)}
45
+ audio = render("beep", sounds=beep, seed=1)
46
+ ```
47
+
48
+ Command line:
49
+
50
+ ```sh
51
+ uppercut-sound-effect-synth --list
52
+ uppercut-sound-effect-synth --out sfx --only whoosh,click --seed 7 --bits 16 --preview
53
+ ```
54
+
55
+ ## Functions
56
+
57
+ | Function | What it does |
58
+ | --- | --- |
59
+ | `render(name, seed=7, take=0, sounds=None, rate=48000, peak_db=-3.0, tail=0.05, width=0.15, channels=2)` | Renders one sound. The generator is seeded from `seed`, `name` and `take`, so a new `take` is a new variation. |
60
+ | `render_pack(out, names=None, seed=7, take=0, sounds=None, rate, bits=24, channels=2, peak_db, preview=False)` | Writes WAV files and `manifest.json`; returns the manifest. |
61
+ | `write_wav(path, x, rate=48000, bits=24)` / `wav_bytes(...)` / `pcm_bytes(x, bits)` | WAV output. `write_wav` returns the SHA-256. |
62
+ | `Rng(seed)`, `derive_seed(seed, *labels)` | Seeded random source: `unit`, `uniform`, `normal`, `white`, `choice`. |
63
+ | `envelope(n, attack, curve, rate)`, `exp_decay(n, time_constant, attack, rate)`, `fade(x, fade_in, fade_out, rate)` | Amplitude shapes. |
64
+ | `lowpass`, `highpass`, `bandpass`, `band_noise(rng, n, low, high)`, `sweep_lowpass(x, f0, f1)` | Filters; Butterworth magnitude response, applied zero-phase. |
65
+ | `tone(freq, n, rate, phase)`, `sweep(f0, f1, n, log=True)` | Sine oscillator with a constant or per-sample frequency; frequency curves. |
66
+ | `saturate(x, drive)`, `mix_into(buf, x, at, gain, rate)`, `finish(x, peak_db, tail, width, channels, rng, rate)`, `seconds(duration, rate)` | Saturation, mixing, final level and stereo width, sample counts. |
67
+
68
+ Built-in names: `whoosh`, `whoosh-short`, `riser`, `impact`, `sub-drop`, `click`, `tick`, `pop`, `shimmer`, `glitch`, `type`, `ding`, `swell`.
69
+
70
+ ## Errors
71
+
72
+ | Error | Raised when |
73
+ | --- | --- |
74
+ | `KeyError` | A sound name is not in the table. |
75
+ | `ValueError` | A cutoff is outside 0 to Nyquist, `bits` is not 8, 16 or 24, `channels` is not 1 or 2, or an argument is out of range. |
76
+
77
+ ## License
78
+
79
+ MIT
@@ -0,0 +1,62 @@
1
+ # uppercut-sound-effect-synth
2
+
3
+ Procedural sound effects that render the same way every time. It provides envelopes, band-limited noise, zero-phase and sweeping filters, pitch sweeps, soft saturation, a seeded random source, 8/16/24-bit WAV writing, thirteen ready-made sounds (whoosh, riser, impact, click, ding and more) and a pack renderer that writes a manifest of SHA-256 hashes. The same seed, sound name and take give identical samples and an identical WAV file on the same NumPy version and platform. The only dependency is NumPy.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pip install uppercut-sound-effect-synth
9
+ ```
10
+
11
+ ## Example
12
+
13
+ ```python
14
+ from uppercut_sound_effect_synth import render, write_wav, render_pack
15
+
16
+ audio = render("impact", seed=7) # (n, 2) float array, peak -3 dBFS
17
+ write_wav("impact.wav", audio) # returns the file's SHA-256
18
+
19
+ render_pack("sfx", ["whoosh", "click"], seed=7, bits=16) # also writes sfx/manifest.json
20
+ ```
21
+
22
+ Your own recipe is a function `(rng, rate) -> 1-D array`:
23
+
24
+ ```python
25
+ from uppercut_sound_effect_synth import render, tone, envelope
26
+
27
+ beep = {"beep": lambda rng, rate: tone(1000, rate // 5, rate) * envelope(rate // 5, 0.002, 2.0, rate)}
28
+ audio = render("beep", sounds=beep, seed=1)
29
+ ```
30
+
31
+ Command line:
32
+
33
+ ```sh
34
+ uppercut-sound-effect-synth --list
35
+ uppercut-sound-effect-synth --out sfx --only whoosh,click --seed 7 --bits 16 --preview
36
+ ```
37
+
38
+ ## Functions
39
+
40
+ | Function | What it does |
41
+ | --- | --- |
42
+ | `render(name, seed=7, take=0, sounds=None, rate=48000, peak_db=-3.0, tail=0.05, width=0.15, channels=2)` | Renders one sound. The generator is seeded from `seed`, `name` and `take`, so a new `take` is a new variation. |
43
+ | `render_pack(out, names=None, seed=7, take=0, sounds=None, rate, bits=24, channels=2, peak_db, preview=False)` | Writes WAV files and `manifest.json`; returns the manifest. |
44
+ | `write_wav(path, x, rate=48000, bits=24)` / `wav_bytes(...)` / `pcm_bytes(x, bits)` | WAV output. `write_wav` returns the SHA-256. |
45
+ | `Rng(seed)`, `derive_seed(seed, *labels)` | Seeded random source: `unit`, `uniform`, `normal`, `white`, `choice`. |
46
+ | `envelope(n, attack, curve, rate)`, `exp_decay(n, time_constant, attack, rate)`, `fade(x, fade_in, fade_out, rate)` | Amplitude shapes. |
47
+ | `lowpass`, `highpass`, `bandpass`, `band_noise(rng, n, low, high)`, `sweep_lowpass(x, f0, f1)` | Filters; Butterworth magnitude response, applied zero-phase. |
48
+ | `tone(freq, n, rate, phase)`, `sweep(f0, f1, n, log=True)` | Sine oscillator with a constant or per-sample frequency; frequency curves. |
49
+ | `saturate(x, drive)`, `mix_into(buf, x, at, gain, rate)`, `finish(x, peak_db, tail, width, channels, rng, rate)`, `seconds(duration, rate)` | Saturation, mixing, final level and stereo width, sample counts. |
50
+
51
+ Built-in names: `whoosh`, `whoosh-short`, `riser`, `impact`, `sub-drop`, `click`, `tick`, `pop`, `shimmer`, `glitch`, `type`, `ding`, `swell`.
52
+
53
+ ## Errors
54
+
55
+ | Error | Raised when |
56
+ | --- | --- |
57
+ | `KeyError` | A sound name is not in the table. |
58
+ | `ValueError` | A cutoff is outside 0 to Nyquist, `bits` is not 8, 16 or 24, `channels` is not 1 or 2, or an argument is out of range. |
59
+
60
+ ## License
61
+
62
+ MIT
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "uppercut-sound-effect-synth"
7
+ version = "0.1.0"
8
+ description = "Deterministic procedural sound effects: envelopes, filtered noise, sweeps, seeded variation and WAV output."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
13
+ dependencies = ["numpy>=1.24"]
14
+ keywords = ["sound-effects", "synthesis", "procedural-audio", "wav", "deterministic"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Multimedia :: Sound/Audio :: Sound Synthesis",
20
+ "Typing :: Typed",
21
+ ]
22
+
23
+ [project.urls]
24
+ Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-sound-effect-synth"
25
+
26
+ [project.scripts]
27
+ uppercut-sound-effect-synth = "uppercut_sound_effect_synth.cli:main"
28
+
29
+ [tool.hatch.build.targets.wheel]
30
+ packages = ["src/uppercut_sound_effect_synth"]
31
+
32
+ [tool.hatch.build.targets.sdist]
33
+ include = ["src", "tests", "README.md"]
@@ -0,0 +1,53 @@
1
+ """Deterministic procedural sound effects."""
2
+
3
+ from .dsp import (
4
+ SAMPLE_RATE,
5
+ band_noise,
6
+ bandpass,
7
+ db_to_gain,
8
+ envelope,
9
+ exp_decay,
10
+ fade,
11
+ finish,
12
+ highpass,
13
+ lowpass,
14
+ mix_into,
15
+ saturate,
16
+ seconds,
17
+ sweep,
18
+ sweep_lowpass,
19
+ tone,
20
+ )
21
+ from .pack import render_pack
22
+ from .recipes import SOUNDS, Recipe, render
23
+ from .rng import Rng, derive_seed
24
+ from .wav import pcm_bytes, wav_bytes, write_wav
25
+
26
+ __all__ = [
27
+ "SAMPLE_RATE",
28
+ "SOUNDS",
29
+ "Recipe",
30
+ "Rng",
31
+ "band_noise",
32
+ "bandpass",
33
+ "db_to_gain",
34
+ "derive_seed",
35
+ "envelope",
36
+ "exp_decay",
37
+ "fade",
38
+ "finish",
39
+ "highpass",
40
+ "lowpass",
41
+ "mix_into",
42
+ "pcm_bytes",
43
+ "render",
44
+ "render_pack",
45
+ "saturate",
46
+ "seconds",
47
+ "sweep",
48
+ "sweep_lowpass",
49
+ "tone",
50
+ "wav_bytes",
51
+ "write_wav",
52
+ ]
53
+ __version__ = "0.1.0"
@@ -0,0 +1,46 @@
1
+ """Command line: list sounds or render a pack of WAV files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from typing import Sequence
8
+
9
+ from .pack import render_pack
10
+ from .recipes import SOUNDS
11
+
12
+
13
+ def main(argv: Sequence[str] | None = None) -> int:
14
+ parser = argparse.ArgumentParser(
15
+ prog="uppercut-sound-effect-synth",
16
+ description="Render deterministic procedural sound effects to WAV files.",
17
+ )
18
+ parser.add_argument("--out", help="output folder")
19
+ parser.add_argument("--seed", type=int, default=7)
20
+ parser.add_argument("--take", type=int, default=0, help="variation number; the same take is always identical")
21
+ parser.add_argument("--only", help="comma-separated sound names")
22
+ parser.add_argument("--bits", type=int, choices=[8, 16, 24], default=24)
23
+ parser.add_argument("--mono", action="store_true")
24
+ parser.add_argument("--preview", action="store_true", help="also write _preview.wav with every sound in a row")
25
+ parser.add_argument("--list", action="store_true", help="print the built-in sound names and exit")
26
+ args = parser.parse_args(argv)
27
+ if args.list:
28
+ print("\n".join(SOUNDS))
29
+ return 0
30
+ if not args.out:
31
+ parser.error("--out is required unless --list is given")
32
+ names = [n.strip() for n in args.only.split(",") if n.strip()] if args.only else None
33
+ try:
34
+ manifest = render_pack(
35
+ args.out, names, args.seed, args.take, bits=args.bits, channels=1 if args.mono else 2, preview=args.preview
36
+ )
37
+ except KeyError as error:
38
+ print(f"error: {error.args[0]}", file=sys.stderr)
39
+ return 2
40
+ for name, entry in manifest["sounds"].items(): # type: ignore[union-attr]
41
+ print(f"{name:13} {entry['seconds']:5.2f}s {entry['sha256'][:12]}")
42
+ return 0
43
+
44
+
45
+ if __name__ == "__main__":
46
+ sys.exit(main())
@@ -0,0 +1,206 @@
1
+ """Signal building blocks. Signals are 1-D float64 NumPy arrays in about [-1, 1]."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from .rng import Rng
8
+
9
+ SAMPLE_RATE = 48000
10
+
11
+
12
+ def seconds(duration: float, rate: int = SAMPLE_RATE) -> int:
13
+ """Number of samples in a duration, at least 1."""
14
+ return max(1, int(round(duration * rate)))
15
+
16
+
17
+ def envelope(n: int, attack: float = 0.005, curve: float = 3.0, rate: int = SAMPLE_RATE) -> np.ndarray:
18
+ """Linear attack over `attack` seconds, then a power-curve decay to zero over the rest."""
19
+ if n < 1:
20
+ raise ValueError("n must be at least 1")
21
+ a = max(1, min(int(round(attack * rate)), n - 1)) if n > 1 else 1
22
+ out = np.ones(n)
23
+ out[:a] = np.linspace(0.0, 1.0, a)
24
+ if n > a:
25
+ out[a:] = np.power(np.linspace(1.0, 0.0, n - a), curve)
26
+ return out
27
+
28
+
29
+ def exp_decay(n: int, time_constant: float, attack: float = 0.0, rate: int = SAMPLE_RATE) -> np.ndarray:
30
+ """Optional linear attack, then exp(-t / time_constant)."""
31
+ if time_constant <= 0:
32
+ raise ValueError("time_constant must be positive")
33
+ t = np.arange(n) / rate
34
+ out = np.exp(-t / time_constant)
35
+ if attack > 0:
36
+ a = min(n, max(1, int(round(attack * rate))))
37
+ out[:a] *= np.linspace(0.0, 1.0, a)
38
+ return out
39
+
40
+
41
+ def fade(x: np.ndarray, fade_in: float = 0.0005, fade_out: float = 0.01, rate: int = SAMPLE_RATE) -> np.ndarray:
42
+ """Linear fades at both ends so a sound never starts or stops with a click."""
43
+ n = len(x)
44
+ out = x.copy()
45
+ i = min(n, int(round(fade_in * rate)))
46
+ o = min(n, int(round(fade_out * rate)))
47
+ if i > 0:
48
+ out[:i] *= np.linspace(0.0, 1.0, i, endpoint=False)
49
+ if o > 0:
50
+ out[n - o :] *= np.linspace(1.0, 0.0, o)
51
+ return out
52
+
53
+
54
+ def _response(freqs: np.ndarray, kind: str, cutoff: float | tuple[float, float], order: int) -> np.ndarray:
55
+ def low(fc: float) -> np.ndarray:
56
+ return 1.0 / np.sqrt(1.0 + (freqs / fc) ** (2 * order))
57
+
58
+ def high(fc: float) -> np.ndarray:
59
+ with np.errstate(divide="ignore", invalid="ignore"):
60
+ r = 1.0 / np.sqrt(1.0 + (fc / np.maximum(freqs, 1e-9)) ** (2 * order))
61
+ return r
62
+
63
+ if kind == "low":
64
+ return low(float(cutoff)) # type: ignore[arg-type]
65
+ if kind == "high":
66
+ return high(float(cutoff)) # type: ignore[arg-type]
67
+ lo, hi = cutoff # type: ignore[misc]
68
+ return high(lo) * low(hi)
69
+
70
+
71
+ def _filter(x: np.ndarray, kind: str, cutoff: float | tuple[float, float], order: int, rate: int) -> np.ndarray:
72
+ if order < 1:
73
+ raise ValueError("order must be at least 1")
74
+ n = len(x)
75
+ size = 1 << int(np.ceil(np.log2(max(2 * n, 2))))
76
+ spectrum = np.fft.rfft(x, size)
77
+ freqs = np.fft.rfftfreq(size, 1.0 / rate)
78
+ return np.fft.irfft(spectrum * _response(freqs, kind, cutoff, order), size)[:n]
79
+
80
+
81
+ def lowpass(x: np.ndarray, cutoff: float, order: int = 4, rate: int = SAMPLE_RATE) -> np.ndarray:
82
+ """Zero-phase low-pass with a Butterworth magnitude response of the given order."""
83
+ _check_cutoff(cutoff, rate)
84
+ return _filter(x, "low", cutoff, order, rate)
85
+
86
+
87
+ def highpass(x: np.ndarray, cutoff: float, order: int = 4, rate: int = SAMPLE_RATE) -> np.ndarray:
88
+ _check_cutoff(cutoff, rate)
89
+ return _filter(x, "high", cutoff, order, rate)
90
+
91
+
92
+ def bandpass(x: np.ndarray, low: float, high: float, order: int = 4, rate: int = SAMPLE_RATE) -> np.ndarray:
93
+ """Zero-phase band-pass between `low` and `high` Hz."""
94
+ if low >= high:
95
+ raise ValueError("low must be below high")
96
+ _check_cutoff(low, rate)
97
+ _check_cutoff(high, rate)
98
+ return _filter(x, "band", (low, high), order, rate)
99
+
100
+
101
+ def _check_cutoff(cutoff: float, rate: int) -> None:
102
+ if not 0 < cutoff < rate / 2:
103
+ raise ValueError(f"cutoff {cutoff} must be between 0 and the Nyquist frequency {rate / 2}")
104
+
105
+
106
+ def band_noise(rng: Rng, n: int, low: float, high: float, rate: int = SAMPLE_RATE) -> np.ndarray:
107
+ """White noise band-limited to `low`..`high` Hz (clamped to 20 Hz and just under Nyquist)."""
108
+ lo = max(low, 20.0)
109
+ hi = min(high, rate / 2 - 100.0)
110
+ return bandpass(rng.white(n), lo, hi, rate=rate)
111
+
112
+
113
+ def sweep_lowpass(
114
+ x: np.ndarray, f0: float, f1: float, order: int = 2, block: int = 512, rate: int = SAMPLE_RATE
115
+ ) -> np.ndarray:
116
+ """A low-pass whose cutoff moves from `f0` to `f1` Hz (geometrically) over the signal.
117
+
118
+ Done by overlap-adding Hann-windowed blocks, each filtered at its own cutoff.
119
+ """
120
+ _check_cutoff(f0, rate)
121
+ _check_cutoff(f1, rate)
122
+ n = len(x)
123
+ hop = block
124
+ padded = np.concatenate([np.zeros(hop), x, np.zeros(2 * hop)])
125
+ window = 0.5 - 0.5 * np.cos(2.0 * np.pi * np.arange(2 * hop) / (2 * hop)) # periodic Hann, sums to 1 at hop
126
+ count = (n + hop) // hop + 1
127
+ cutoffs = np.geomspace(f0, f1, count)
128
+ size = 4 * hop
129
+ out = np.zeros(len(padded) + size)
130
+ freqs = np.fft.rfftfreq(size, 1.0 / rate)
131
+ for k in range(count):
132
+ start = k * hop
133
+ seg = padded[start : start + 2 * hop] * window
134
+ if len(seg) < 2 * hop:
135
+ break
136
+ filtered = np.fft.irfft(np.fft.rfft(seg, size) * _response(freqs, "low", cutoffs[k], order), size)
137
+ out[start : start + size] += filtered
138
+ return out[hop : hop + n]
139
+
140
+
141
+ def sweep(f0: float, f1: float, n: int, log: bool = True) -> np.ndarray:
142
+ """A frequency curve of `n` samples from f0 to f1 Hz, geometric by default."""
143
+ if log:
144
+ if f0 <= 0 or f1 <= 0:
145
+ raise ValueError("log sweeps need positive frequencies")
146
+ return np.geomspace(f0, f1, n)
147
+ return np.linspace(f0, f1, n)
148
+
149
+
150
+ def tone(freq: float | np.ndarray, n: int, rate: int = SAMPLE_RATE, phase: float = 0.0) -> np.ndarray:
151
+ """A sine whose frequency is a constant or a per-sample curve. Phase is continuous."""
152
+ f = np.full(n, float(freq)) if np.isscalar(freq) else np.asarray(freq, dtype=float)
153
+ if len(f) != n:
154
+ raise ValueError("frequency curve must have n samples")
155
+ return np.sin(2.0 * np.pi * (np.cumsum(f) / rate + phase))
156
+
157
+
158
+ def saturate(x: np.ndarray, drive: float = 2.0) -> np.ndarray:
159
+ """Soft clip: tanh of the signal after a gain of `drive`. Output stays within -1 to 1."""
160
+ return np.tanh(x * drive)
161
+
162
+
163
+ def mix_into(buf: np.ndarray, x: np.ndarray, at: float, gain: float = 1.0, rate: int = SAMPLE_RATE) -> None:
164
+ """Add `x` into `buf` starting `at` seconds, cut at the end of `buf`."""
165
+ i = int(round(at * rate))
166
+ if i < 0:
167
+ raise ValueError("at must not be negative")
168
+ if i >= len(buf):
169
+ return
170
+ m = min(len(x), len(buf) - i)
171
+ buf[i : i + m] += x[:m] * gain
172
+
173
+
174
+ def db_to_gain(db: float) -> float:
175
+ return 10.0 ** (db / 20.0)
176
+
177
+
178
+ def finish(
179
+ x: np.ndarray,
180
+ peak_db: float = -3.0,
181
+ tail: float = 0.05,
182
+ width: float = 0.15,
183
+ channels: int = 2,
184
+ rng: Rng | None = None,
185
+ rate: int = SAMPLE_RATE,
186
+ ) -> np.ndarray:
187
+ """The last step of a sound: a silent tail, a fixed peak level and optional stereo width.
188
+
189
+ Returns shape (n,) for one channel or (n, 2) for two. Stereo width is a tiny delay on
190
+ the right channel (random in 0.2 to 0.6 ms when `rng` is given, else 0.4 ms) blended
191
+ with the dry signal by `width`. Silence stays silence.
192
+ """
193
+ if channels not in (1, 2):
194
+ raise ValueError("channels must be 1 or 2")
195
+ if peak_db > 0:
196
+ raise ValueError("peak_db must be 0 or below")
197
+ y = np.concatenate([x, np.zeros(int(round(tail * rate)))])
198
+ peak = float(np.max(np.abs(y))) if len(y) else 0.0
199
+ if peak > 0:
200
+ y = y / peak * db_to_gain(peak_db)
201
+ if channels == 1:
202
+ return y
203
+ delay = int(round((rng.uniform(0.0002, 0.0006) if rng else 0.0004) * rate))
204
+ delay = max(1, min(delay, max(len(y) - 1, 1)))
205
+ right = np.concatenate([np.zeros(delay), y[:-delay]]) * (1.0 - width) + y * width
206
+ return np.stack([y, right], axis=1)
@@ -0,0 +1,63 @@
1
+ """Render a set of sounds to WAV files with a manifest of SHA-256 hashes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Mapping, Sequence
8
+
9
+ import numpy as np
10
+
11
+ from . import dsp
12
+ from .recipes import SOUNDS, Recipe, render
13
+ from .wav import write_wav
14
+
15
+
16
+ def render_pack(
17
+ out: str | Path,
18
+ names: Sequence[str] | None = None,
19
+ seed: int = 7,
20
+ take: int = 0,
21
+ *,
22
+ sounds: Mapping[str, Recipe] | None = None,
23
+ rate: int = dsp.SAMPLE_RATE,
24
+ bits: int = 24,
25
+ channels: int = 2,
26
+ peak_db: float = -3.0,
27
+ preview: bool = False,
28
+ gap: float = 0.5,
29
+ ) -> dict[str, object]:
30
+ """Write `<name>.wav` for each sound into `out` and a `manifest.json` beside them.
31
+
32
+ `names` selects sounds (default: all). `sounds` replaces the built-in table with your
33
+ own recipes. With `preview`, `_preview.wav` plays every sound in a row, `gap` seconds apart.
34
+ Returns the manifest: settings plus, per sound, its file, duration and SHA-256.
35
+ """
36
+ table = SOUNDS if sounds is None else sounds
37
+ chosen = list(table) if names is None else list(names)
38
+ unknown = [n for n in chosen if n not in table]
39
+ if unknown:
40
+ raise KeyError(f"unknown sound {unknown[0]!r}; choose from {', '.join(sorted(table))}")
41
+ folder = Path(out)
42
+ folder.mkdir(parents=True, exist_ok=True)
43
+ entries: dict[str, dict[str, object]] = {}
44
+ parts: list[np.ndarray] = []
45
+ for name in chosen:
46
+ audio = render(name, seed, take, sounds=table, rate=rate, peak_db=peak_db, channels=channels)
47
+ file = f"{name}.wav"
48
+ digest = write_wav(folder / file, audio, rate, bits)
49
+ entries[name] = {"file": file, "seconds": round(len(audio) / rate, 4), "sha256": digest}
50
+ parts += [audio, np.zeros((int(gap * rate),) + audio.shape[1:])]
51
+ if preview and parts:
52
+ write_wav(folder / "_preview.wav", np.concatenate(parts), rate, bits)
53
+ manifest: dict[str, object] = {
54
+ "seed": seed,
55
+ "take": take,
56
+ "rate": rate,
57
+ "bits": bits,
58
+ "channels": channels,
59
+ "peak_db": peak_db,
60
+ "sounds": entries,
61
+ }
62
+ (folder / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
63
+ return manifest
@@ -0,0 +1,150 @@
1
+ """Built-in sound recipes and the render functions that make them reproducible.
2
+
3
+ A recipe is a function `(rng, rate) -> 1-D array`. `render` seeds the generator from a base
4
+ seed, the sound name and a take number, so a given (seed, name, take) always gives the same
5
+ samples and a different take gives a different variation of the same sound.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Callable, Mapping
11
+
12
+ import numpy as np
13
+
14
+ from . import dsp
15
+ from .rng import Rng, derive_seed
16
+
17
+ Recipe = Callable[[Rng, int], np.ndarray]
18
+
19
+
20
+ def whoosh(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 0.7, up: bool = True) -> np.ndarray:
21
+ n = dsp.seconds(duration, rate)
22
+ x = dsp.sweep_lowpass(rng.white(n), 300 if up else 6000, 6000 if up else 300, rate=rate)
23
+ return x * np.sin(np.pi * np.linspace(0, 1, n)) ** 2
24
+
25
+
26
+ def riser(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 1.6) -> np.ndarray:
27
+ n = dsp.seconds(duration, rate)
28
+ ramp = np.linspace(0, 1, n) ** 2
29
+ noise = dsp.sweep_lowpass(rng.white(n), 200, 9000, rate=rate) * ramp
30
+ return noise + dsp.tone(dsp.sweep(180, 900, n), n, rate) * ramp * 0.5
31
+
32
+
33
+ def impact(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 0.9) -> np.ndarray:
34
+ n = dsp.seconds(duration, rate)
35
+ f = dsp.sweep(58, 41, n)
36
+ sub = dsp.tone(f, n, rate) * dsp.envelope(n, 0.004, 2.2, rate)
37
+ harmonic = 0.35 * dsp.tone(f * 2, n, rate) * dsp.envelope(n, 0.004, 4.0, rate)
38
+ click = dsp.band_noise(rng, n, 1500, 8000, rate) * dsp.envelope(n, 0.0004, 12.0, rate) * 0.6
39
+ return sub + harmonic + click
40
+
41
+
42
+ def sub_drop(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 1.2) -> np.ndarray:
43
+ n = dsp.seconds(duration, rate)
44
+ return dsp.tone(dsp.sweep(90, 30, n), n, rate) * dsp.envelope(n, 0.01, 1.6, rate)
45
+
46
+
47
+ def click(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 0.08) -> np.ndarray:
48
+ n = dsp.seconds(duration, rate)
49
+ return dsp.band_noise(rng, n, 2000, 12000, rate) * dsp.envelope(n, 0.0002, 10.0, rate)
50
+
51
+
52
+ def tick(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 0.05) -> np.ndarray:
53
+ n = dsp.seconds(duration, rate)
54
+ return dsp.tone(2400.0, n, rate) * dsp.envelope(n, 0.0001, 6.0, rate)
55
+
56
+
57
+ def pop(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 0.12) -> np.ndarray:
58
+ n = dsp.seconds(duration, rate)
59
+ return dsp.tone(dsp.sweep(900, 280, n), n, rate) * dsp.envelope(n, 0.0004, 5.0, rate)
60
+
61
+
62
+ def shimmer(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 1.0) -> np.ndarray:
63
+ n = dsp.seconds(duration, rate)
64
+ t = np.arange(n) / rate
65
+ x = np.zeros(n)
66
+ for k in range(7):
67
+ freq = rng.uniform(2500, 7000)
68
+ vibrato = 1 + 0.004 * np.sin(2 * np.pi * rng.uniform(4, 7) * t)
69
+ phase = rng.uniform(0, 1)
70
+ x += dsp.tone(freq * vibrato, n, rate, phase) / (k + 2)
71
+ return x * dsp.envelope(n, 0.05, 2.5, rate)
72
+
73
+
74
+ def glitch(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 0.35) -> np.ndarray:
75
+ n = dsp.seconds(duration, rate)
76
+ x = np.zeros(n)
77
+ pos = 0
78
+ while pos < n:
79
+ length = min(int(rng.uniform(0.01, 0.05) * rate), n - pos)
80
+ freq = rng.choice([220, 440, 880, 1760, 3520])
81
+ square = np.sign(np.sin(2 * np.pi * freq * np.arange(length) / rate)) * rng.uniform(0.2, 1.0)
82
+ x[pos : pos + length] = np.round(square * 4) / 4
83
+ pos += length + int(rng.uniform(0, 0.02) * rate)
84
+ return x * dsp.envelope(n, 0.0001, 1.0, rate)
85
+
86
+
87
+ def typing(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 0.6, keys: int = 7) -> np.ndarray:
88
+ n = dsp.seconds(duration, rate)
89
+ x = np.zeros(n)
90
+ m = int(0.03 * rate)
91
+ for start in np.sort(rng.uniform(0, duration - 0.05, keys)):
92
+ key = dsp.band_noise(rng, m, 1800, 9000, rate) * dsp.envelope(m, 0.0001, 8.0, rate) * rng.uniform(0.5, 1.0)
93
+ i = int(start * rate)
94
+ x[i : i + m] += key[: n - i]
95
+ return x
96
+
97
+
98
+ def ding(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 1.4) -> np.ndarray:
99
+ n = dsp.seconds(duration, rate)
100
+ partials = ((1320, 1.0), (2640, 0.35), (3960, 0.15), (1980, 0.2))
101
+ bell = sum(dsp.tone(f, n, rate) * a for f, a in partials)
102
+ return bell * dsp.envelope(n, 0.0006, 3.0, rate)
103
+
104
+
105
+ def swell(rng: Rng, rate: int = dsp.SAMPLE_RATE, duration: float = 1.8) -> np.ndarray:
106
+ n = dsp.seconds(duration, rate)
107
+ pad = sum(dsp.tone(f, n, rate, rng.uniform(0, 1)) for f in (220.0, 277.2, 329.6, 440.0))
108
+ return pad * np.sin(np.pi * np.linspace(0, 1, n)) ** 1.5
109
+
110
+
111
+ SOUNDS: dict[str, Recipe] = {
112
+ "whoosh": lambda r, sr: whoosh(r, sr, 0.7, True),
113
+ "whoosh-short": lambda r, sr: whoosh(r, sr, 0.35, False),
114
+ "riser": riser,
115
+ "impact": impact,
116
+ "sub-drop": sub_drop,
117
+ "click": click,
118
+ "tick": tick,
119
+ "pop": pop,
120
+ "shimmer": shimmer,
121
+ "glitch": glitch,
122
+ "type": typing,
123
+ "ding": ding,
124
+ "swell": swell,
125
+ }
126
+
127
+
128
+ def render(
129
+ name: str,
130
+ seed: int = 7,
131
+ take: int = 0,
132
+ *,
133
+ sounds: Mapping[str, Recipe] | None = None,
134
+ rate: int = dsp.SAMPLE_RATE,
135
+ peak_db: float = -3.0,
136
+ tail: float = 0.05,
137
+ width: float = 0.15,
138
+ channels: int = 2,
139
+ ) -> np.ndarray:
140
+ """Render one sound to a finished array: shape (n,) for mono or (n, 2) for stereo.
141
+
142
+ The same (seed, name, take, options) always gives the same array. Raises KeyError for an
143
+ unknown name.
144
+ """
145
+ table = SOUNDS if sounds is None else sounds
146
+ if name not in table:
147
+ raise KeyError(f"unknown sound {name!r}; choose from {', '.join(sorted(table))}")
148
+ rng = Rng(derive_seed(seed, name, take))
149
+ raw = table[name](rng, rate)
150
+ return dsp.finish(raw, peak_db=peak_db, tail=tail, width=width, channels=channels, rng=rng, rate=rate)
@@ -0,0 +1,61 @@
1
+ """A small seeded random source built on the PCG64 bit stream.
2
+
3
+ NumPy documents the raw PCG64 bit stream as stable, so this module turns raw 64-bit
4
+ integers into floats itself instead of relying on `Generator` methods whose output
5
+ may change between NumPy releases.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ from typing import Sequence, TypeVar
12
+
13
+ import numpy as np
14
+
15
+ T = TypeVar("T")
16
+
17
+
18
+ def derive_seed(seed: int, *labels: object) -> int:
19
+ """A 64-bit seed derived from a base seed and labels such as a sound name and take number."""
20
+ text = ":".join([str(int(seed)), *[str(label) for label in labels]])
21
+ return int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "little")
22
+
23
+
24
+ class Rng:
25
+ """Seeded random numbers. The same seed gives the same sequence."""
26
+
27
+ def __init__(self, seed: int) -> None:
28
+ self.seed = int(seed)
29
+ self._bits = np.random.PCG64(self.seed & ((1 << 64) - 1))
30
+
31
+ def unit(self, size: int | None = None) -> float | np.ndarray:
32
+ """Uniform in [0, 1)."""
33
+ count = 1 if size is None else int(size)
34
+ raw = self._bits.random_raw(count) if count else np.empty(0, dtype=np.uint64)
35
+ values = (raw >> np.uint64(11)).astype(np.float64) * (1.0 / 9007199254740992.0)
36
+ return float(values[0]) if size is None else values
37
+
38
+ def uniform(self, low: float, high: float, size: int | None = None) -> float | np.ndarray:
39
+ values = low + (high - low) * self.unit(size)
40
+ return float(values) if size is None else values
41
+
42
+ def normal(self, size: int) -> np.ndarray:
43
+ """Standard normal samples (Box-Muller)."""
44
+ count = int(size)
45
+ pairs = (count + 1) // 2
46
+ u1 = 1.0 - self.unit(pairs) # in (0, 1]
47
+ u2 = self.unit(pairs)
48
+ radius = np.sqrt(-2.0 * np.log(u1))
49
+ out = np.empty(pairs * 2)
50
+ out[0::2] = radius * np.cos(2.0 * np.pi * u2)
51
+ out[1::2] = radius * np.sin(2.0 * np.pi * u2)
52
+ return out[:count]
53
+
54
+ def white(self, size: int) -> np.ndarray:
55
+ """White noise with unit variance."""
56
+ return self.normal(size)
57
+
58
+ def choice(self, options: Sequence[T]) -> T:
59
+ if not options:
60
+ raise ValueError("choice needs at least one option")
61
+ return options[min(int(self.unit() * len(options)), len(options) - 1)]
@@ -0,0 +1,51 @@
1
+ """WAV encoding with the standard library only. The same samples always give the same bytes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import struct
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+ from .dsp import SAMPLE_RATE
12
+
13
+
14
+ def pcm_bytes(x: np.ndarray, bits: int = 24) -> bytes:
15
+ """Interleaved little-endian PCM. 8-bit is unsigned, 16 and 24 are signed. Clips at full scale."""
16
+ if bits not in (8, 16, 24):
17
+ raise ValueError("bits must be 8, 16 or 24")
18
+ a = np.clip(np.asarray(x, dtype=np.float64), -1.0, 1.0)
19
+ if bits == 8:
20
+ return np.round(a * 127.0 + 128.0).astype(np.uint8).tobytes()
21
+ scale = float(2 ** (bits - 1) - 1)
22
+ ints = np.round(a * scale).astype(np.int32)
23
+ if bits == 16:
24
+ return ints.astype("<i2").tobytes()
25
+ raw = ints.astype("<i4").tobytes()
26
+ return b"".join(raw[i : i + 3] for i in range(0, len(raw), 4))
27
+
28
+
29
+ def wav_bytes(x: np.ndarray, rate: int = SAMPLE_RATE, bits: int = 24) -> bytes:
30
+ """A complete WAV file for samples shaped (n,) or (n, channels)."""
31
+ a = np.asarray(x)
32
+ if a.ndim == 1:
33
+ channels = 1
34
+ elif a.ndim == 2 and 1 <= a.shape[1] <= 8:
35
+ channels = a.shape[1]
36
+ else:
37
+ raise ValueError("samples must be shaped (n,) or (n, channels) with 1 to 8 channels")
38
+ data = pcm_bytes(a, bits)
39
+ block = channels * bits // 8
40
+ header = b"RIFF" + struct.pack("<I", 36 + len(data)) + b"WAVE"
41
+ fmt = b"fmt " + struct.pack("<IHHIIHH", 16, 1, channels, rate, rate * block, block, bits)
42
+ return header + fmt + b"data" + struct.pack("<I", len(data)) + data + (b"\x00" if len(data) % 2 else b"")
43
+
44
+
45
+ def write_wav(path: str | Path, x: np.ndarray, rate: int = SAMPLE_RATE, bits: int = 24) -> str:
46
+ """Write a WAV file and return its SHA-256 hex digest."""
47
+ data = wav_bytes(x, rate, bits)
48
+ target = Path(path)
49
+ target.parent.mkdir(parents=True, exist_ok=True)
50
+ target.write_bytes(data)
51
+ return hashlib.sha256(data).hexdigest()
@@ -0,0 +1,271 @@
1
+ import hashlib
2
+ import json
3
+ import wave
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from uppercut_sound_effect_synth import (
9
+ SOUNDS,
10
+ Rng,
11
+ band_noise,
12
+ bandpass,
13
+ derive_seed,
14
+ envelope,
15
+ exp_decay,
16
+ fade,
17
+ finish,
18
+ highpass,
19
+ lowpass,
20
+ mix_into,
21
+ pcm_bytes,
22
+ render,
23
+ render_pack,
24
+ saturate,
25
+ seconds,
26
+ sweep,
27
+ sweep_lowpass,
28
+ tone,
29
+ wav_bytes,
30
+ write_wav,
31
+ )
32
+ from uppercut_sound_effect_synth.cli import main as cli_main
33
+
34
+ RATE = 48000
35
+
36
+
37
+ def band_power(x, lo, hi):
38
+ spec = np.abs(np.fft.rfft(x)) ** 2
39
+ freqs = np.fft.rfftfreq(len(x), 1 / RATE)
40
+ return float(spec[(freqs >= lo) & (freqs < hi)].sum())
41
+
42
+
43
+ # ---- determinism (the main guarantee) ---------------------------------------------
44
+
45
+
46
+ @pytest.mark.parametrize("name", list(SOUNDS))
47
+ def test_same_seed_gives_identical_bytes(name):
48
+ a = wav_bytes(render(name, seed=7), RATE, 24)
49
+ b = wav_bytes(render(name, seed=7), RATE, 24)
50
+ assert a == b
51
+ assert hashlib.sha256(a).digest() == hashlib.sha256(b).digest()
52
+
53
+
54
+ def test_different_seed_or_take_changes_noise_sounds():
55
+ base = wav_bytes(render("whoosh", seed=7))
56
+ assert wav_bytes(render("whoosh", seed=8)) != base
57
+ assert wav_bytes(render("whoosh", seed=7, take=1)) != base
58
+
59
+
60
+ def test_pack_is_byte_identical_across_runs(tmp_path):
61
+ m1 = render_pack(tmp_path / "a", seed=3)
62
+ m2 = render_pack(tmp_path / "b", seed=3)
63
+ assert m1 == m2
64
+ for name in SOUNDS:
65
+ assert (tmp_path / "a" / f"{name}.wav").read_bytes() == (tmp_path / "b" / f"{name}.wav").read_bytes()
66
+ assert (tmp_path / "a" / "manifest.json").read_bytes() == (tmp_path / "b" / "manifest.json").read_bytes()
67
+
68
+
69
+ def test_rng_sequences():
70
+ a, b = Rng(5), Rng(5)
71
+ assert np.array_equal(a.white(100), b.white(100))
72
+ assert a.unit() == b.unit()
73
+ assert not np.array_equal(Rng(5).white(50), Rng(6).white(50))
74
+
75
+
76
+ def test_rng_ranges_and_stats():
77
+ r = Rng(1)
78
+ u = r.unit(20000)
79
+ assert u.min() >= 0 and u.max() < 1 and abs(u.mean() - 0.5) < 0.02
80
+ n = Rng(2).normal(20001)
81
+ assert len(n) == 20001 and abs(n.mean()) < 0.05 and abs(n.std() - 1) < 0.05
82
+ assert 3.0 <= r.uniform(3.0, 4.0) < 4.0
83
+ assert r.choice(["a"]) == "a"
84
+ assert Rng(3).unit(0).shape == (0,)
85
+ with pytest.raises(ValueError):
86
+ r.choice([])
87
+
88
+
89
+ def test_derive_seed_is_stable_and_label_sensitive():
90
+ assert derive_seed(7, "whoosh", 0) == derive_seed(7, "whoosh", 0)
91
+ assert derive_seed(7, "whoosh", 0) != derive_seed(7, "whoosh", 1)
92
+ assert derive_seed(7, "a") != derive_seed(8, "a")
93
+
94
+
95
+ # ---- DSP --------------------------------------------------------------------------
96
+
97
+
98
+ def test_envelope_shape():
99
+ e = envelope(1000, attack=0.001, curve=2.0, rate=RATE)
100
+ assert e[0] == 0 and e.max() == pytest.approx(1.0, abs=0.02)
101
+ assert e[-1] == pytest.approx(0.0, abs=1e-9)
102
+ assert np.all(np.diff(e[60:]) <= 1e-12)
103
+ assert len(envelope(1)) == 1
104
+ with pytest.raises(ValueError):
105
+ envelope(0)
106
+
107
+
108
+ def test_exp_decay():
109
+ e = exp_decay(RATE, 0.1, attack=0.01, rate=RATE)
110
+ assert e[0] == 0 and e[RATE // 2] == pytest.approx(np.exp(-5), rel=0.05)
111
+ with pytest.raises(ValueError):
112
+ exp_decay(10, 0)
113
+
114
+
115
+ def test_filters_pass_and_stop():
116
+ x = tone(100, RATE) + tone(8000, RATE)
117
+ low = lowpass(x, 1000, rate=RATE)
118
+ assert band_power(low, 7000, 9000) < 1e-3 * band_power(low, 50, 150)
119
+ high = highpass(x, 2000, rate=RATE)
120
+ assert band_power(high, 50, 150) < 1e-3 * band_power(high, 7000, 9000)
121
+ band = bandpass(x + tone(1000, RATE), 800, 1200, rate=RATE)
122
+ assert band_power(band, 900, 1100) > 100 * band_power(band, 50, 150)
123
+ assert len(low) == len(x)
124
+
125
+
126
+ def test_filter_errors():
127
+ x = np.zeros(100)
128
+ with pytest.raises(ValueError):
129
+ lowpass(x, 30000)
130
+ with pytest.raises(ValueError):
131
+ bandpass(x, 2000, 1000)
132
+ with pytest.raises(ValueError):
133
+ lowpass(x, 100, order=0)
134
+
135
+
136
+ def test_band_noise_is_band_limited_and_seeded():
137
+ n = band_noise(Rng(1), 8192, 2000, 6000)
138
+ assert band_power(n, 2000, 6000) > 20 * band_power(n, 0, 500)
139
+ assert np.array_equal(n, band_noise(Rng(1), 8192, 2000, 6000))
140
+
141
+
142
+ def test_sweep_lowpass_darkens_over_time():
143
+ x = Rng(1).white(RATE)
144
+ y = sweep_lowpass(x, 8000, 300)
145
+ assert len(y) == len(x)
146
+ first, last = y[: RATE // 4], y[-RATE // 4 :]
147
+ assert band_power(first, 4000, 20000) > 10 * band_power(last, 4000, 20000)
148
+ assert np.isfinite(y).all()
149
+
150
+
151
+ def test_sweep_and_tone():
152
+ f = sweep(100, 1000, 5)
153
+ assert f[0] == pytest.approx(100) and f[-1] == pytest.approx(1000)
154
+ assert sweep(100, 200, 3, log=False).tolist() == [100, 150, 200]
155
+ with pytest.raises(ValueError):
156
+ sweep(0, 100, 5)
157
+ t = tone(440, 480, RATE)
158
+ assert abs(t).max() <= 1.0 and len(t) == 480
159
+ with pytest.raises(ValueError):
160
+ tone(np.ones(3), 5)
161
+
162
+
163
+ def test_saturate_bounds_and_small_signal():
164
+ big = saturate(np.array([-10.0, 10.0]), 3)
165
+ assert np.all(np.abs(big) <= 1.0 + 1e-12)
166
+ small = saturate(np.array([0.001]), 2)
167
+ assert small[0] == pytest.approx(0.002, rel=1e-3)
168
+
169
+
170
+ def test_fade_and_mix_into():
171
+ x = np.ones(1000)
172
+ y = fade(x, 0.001, 0.002, RATE)
173
+ assert y[0] == 0 and y[-1] == 0 and y[500] == 1
174
+ buf = np.zeros(100)
175
+ mix_into(buf, np.ones(50), at=60 / RATE, rate=RATE)
176
+ assert buf[:60].sum() == 0 and buf[60:].sum() == 40
177
+ mix_into(buf, np.ones(5), at=10.0, rate=RATE)
178
+ with pytest.raises(ValueError):
179
+ mix_into(buf, np.ones(5), at=-1)
180
+
181
+
182
+ def test_seconds_helper():
183
+ assert seconds(0.5, RATE) == 24000
184
+ assert seconds(0.0, RATE) == 1
185
+
186
+
187
+ def test_finish_levels_and_shape():
188
+ y = finish(np.sin(np.linspace(0, 100, 4800)) * 0.2, peak_db=-6, tail=0.01)
189
+ assert y.shape == (4800 + 480, 2)
190
+ assert np.abs(y).max() == pytest.approx(10 ** (-6 / 20), rel=1e-6)
191
+ assert np.all(y[-400:] == 0)
192
+ mono = finish(np.ones(100), channels=1)
193
+ assert mono.ndim == 1
194
+ silent = finish(np.zeros(100), channels=1)
195
+ assert np.all(silent == 0)
196
+ with pytest.raises(ValueError):
197
+ finish(np.ones(10), channels=3)
198
+ with pytest.raises(ValueError):
199
+ finish(np.ones(10), peak_db=2)
200
+
201
+
202
+ # ---- WAV -----------------------------------------------------------------------------
203
+
204
+
205
+ @pytest.mark.parametrize("bits", [8, 16, 24])
206
+ def test_wav_roundtrip_header(tmp_path, bits):
207
+ audio = render("click", seed=1, channels=2)
208
+ digest = write_wav(tmp_path / "x.wav", audio, RATE, bits)
209
+ data = (tmp_path / "x.wav").read_bytes()
210
+ assert hashlib.sha256(data).hexdigest() == digest
211
+ with wave.open(str(tmp_path / "x.wav")) as w:
212
+ assert w.getnchannels() == 2 and w.getframerate() == RATE and w.getsampwidth() == bits // 8
213
+ assert w.getnframes() == len(audio)
214
+
215
+
216
+ def test_pcm_values():
217
+ assert pcm_bytes(np.array([0.0, 1.0, -1.0, 2.0]), 16) == np.array([0, 32767, -32767, 32767], "<i2").tobytes()
218
+ assert pcm_bytes(np.array([0.0, 1.0, -1.0]), 8) == bytes([128, 255, 1])
219
+ assert pcm_bytes(np.array([1.0, -1.0]), 24) == bytes([0xFF, 0xFF, 0x7F, 0x01, 0x00, 0x80])
220
+ with pytest.raises(ValueError):
221
+ pcm_bytes(np.zeros(3), 12)
222
+
223
+
224
+ def test_wav_bytes_shape_errors():
225
+ with pytest.raises(ValueError):
226
+ wav_bytes(np.zeros((4, 3, 2)))
227
+ assert wav_bytes(np.zeros(5), RATE, 8)[:4] == b"RIFF"
228
+
229
+
230
+ # ---- recipes and packs --------------------------------------------------------------------
231
+
232
+
233
+ @pytest.mark.parametrize("name", list(SOUNDS))
234
+ def test_each_recipe_renders_clean_audio(name):
235
+ y = render(name, seed=7)
236
+ assert y.ndim == 2 and y.shape[1] == 2 and len(y) > 1000
237
+ assert np.isfinite(y).all()
238
+ assert np.abs(y).max() == pytest.approx(10 ** (-3 / 20), rel=1e-6)
239
+
240
+
241
+ def test_render_options_and_errors():
242
+ mono = render("tick", channels=1, peak_db=-12)
243
+ assert mono.ndim == 1 and np.abs(mono).max() == pytest.approx(10 ** (-12 / 20), rel=1e-6)
244
+ with pytest.raises(KeyError, match="unknown sound"):
245
+ render("nope")
246
+
247
+
248
+ def test_custom_recipe_table():
249
+ table = {"beep": lambda rng, rate: tone(1000, rate // 10, rate)}
250
+ y = render("beep", sounds=table, channels=1)
251
+ assert len(y) > RATE // 10
252
+
253
+
254
+ def test_render_pack_writes_manifest_and_preview(tmp_path):
255
+ manifest = render_pack(tmp_path, ["click", "tick"], seed=2, bits=16, channels=1, preview=True)
256
+ assert set(manifest["sounds"]) == {"click", "tick"}
257
+ on_disk = json.loads((tmp_path / "manifest.json").read_text())
258
+ assert on_disk == manifest
259
+ for entry in manifest["sounds"].values():
260
+ assert hashlib.sha256((tmp_path / entry["file"]).read_bytes()).hexdigest() == entry["sha256"]
261
+ assert (tmp_path / "_preview.wav").exists()
262
+ with pytest.raises(KeyError):
263
+ render_pack(tmp_path, ["missing"])
264
+
265
+
266
+ def test_cli(tmp_path, capsys):
267
+ assert cli_main(["--list"]) == 0
268
+ assert "whoosh" in capsys.readouterr().out
269
+ assert cli_main(["--out", str(tmp_path), "--only", "click,pop", "--bits", "16", "--mono"]) == 0
270
+ assert (tmp_path / "click.wav").exists() and (tmp_path / "pop.wav").exists()
271
+ assert cli_main(["--out", str(tmp_path), "--only", "bogus"]) == 2