-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate_all_soundpacks.py
More file actions
executable file
·3902 lines (3274 loc) · 99.6 KB
/
Copy pathgenerate_all_soundpacks.py
File metadata and controls
executable file
·3902 lines (3274 loc) · 99.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
LeanType Sound Pack Generator
Generates 10 algorithmically synthesized LeanType sound packs, packages them
into zip archives with pack.json, calculates SHA-256 checksums, and produces
a root index.json for direct raw repository download.
Requirements:
pip install numpy scipy soundfile
Usage:
python generate_all_soundpacks.py \
--base-url https://raw.githubusercontent.com/YOUR_USER/leantype-soundpacks/main/dist
Notes:
- Output format is OGG/Vorbis when supported by libsndfile.
- If OGG is unavailable, output automatically falls back to WAV.
- All sounds are mono, 48 kHz, short, peak-normalized to about -2 dBFS,
and trimmed/faded to avoid leading silence and edge clicks.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
import sys
import tempfile
import zipfile
import zlib
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Dict, List, Tuple
import numpy as np
from scipy.signal import butter, sosfilt
import soundfile as sf
SAMPLE_RATE = 48000
TARGET_PEAK_DB = -2.0
MIN_DURATION = 0.025
MAX_DURATION = 0.150
MAX_AUDIO_FILE_BYTES = 500 * 1024
MAX_PACK_ZIP_BYTES = 2 * 1024 * 1024
# ----------------------------------------------------------------------------
# Basic helpers
# ----------------------------------------------------------------------------
def db_to_linear(db: float) -> float:
return float(10.0 ** (db / 20.0))
def clamp_freq(freq: float) -> float:
nyq = SAMPLE_RATE / 2.0
return float(max(20.0, min(freq, nyq - 100.0)))
def child_rng(rng: np.random.Generator, salt: int = 0) -> np.random.Generator:
seed = int(rng.integers(0, 2**32 - 1))
seed = (seed + salt * 2654435761) % (2**32)
return np.random.default_rng(seed)
def finalize(
audio: np.ndarray,
target_db: float = TARGET_PEAK_DB,
fade_in_ms: float = 0.4,
fade_out_ms: float = 2.0,
) -> np.ndarray:
"""
Normalize, remove DC, enforce max duration, and apply tiny fades.
"""
audio = np.asarray(audio, dtype=np.float64)
if audio.ndim > 1:
audio = np.mean(audio, axis=0)
if audio.size == 0:
return np.zeros(int(MIN_DURATION * SAMPLE_RATE), dtype=np.float32)
max_samples = int(MAX_DURATION * SAMPLE_RATE)
if len(audio) > max_samples:
audio = audio[:max_samples]
audio = audio - float(np.mean(audio))
n = len(audio)
fade_in_samples = int(fade_in_ms * 0.001 * SAMPLE_RATE)
fade_out_samples = int(fade_out_ms * 0.001 * SAMPLE_RATE)
if fade_in_samples > 0:
fade_in_samples = min(fade_in_samples, max(1, n // 2))
audio[:fade_in_samples] *= np.linspace(0.0, 1.0, fade_in_samples)
if fade_out_samples > 0:
fade_out_samples = min(fade_out_samples, max(1, n // 2))
audio[-fade_out_samples:] *= np.linspace(1.0, 0.0, fade_out_samples)
peak = float(np.max(np.abs(audio))) if n else 0.0
if peak > 1e-9:
audio *= db_to_linear(target_db) / peak
return audio.astype(np.float32)
def noise(rng: np.random.Generator, duration: float) -> np.ndarray:
n = max(1, int(round(duration * SAMPLE_RATE)))
return rng.standard_normal(n)
def decay_env(duration: float, tau: float, attack_s: float = 0.0004) -> np.ndarray:
n = max(1, int(round(duration * SAMPLE_RATE)))
t = np.arange(n, dtype=np.float64) / SAMPLE_RATE
if tau <= 0:
tau = max(duration / 6.0, 0.001)
env = np.exp(-t / tau)
attack_samples = max(1, int(attack_s * SAMPLE_RATE))
if attack_samples > 1 and attack_samples < n:
env[:attack_samples] *= np.linspace(0.0, 1.0, attack_samples)
return env
def apply_sos(audio: np.ndarray, sos: np.ndarray) -> np.ndarray:
if len(audio) < 16:
return audio
return sosfilt(sos, audio)
def lowpass(audio: np.ndarray, cutoff: float, order: int = 3) -> np.ndarray:
cutoff = clamp_freq(cutoff)
nyq = SAMPLE_RATE / 2.0
if cutoff >= nyq - 100.0:
return audio
sos = butter(order, cutoff / nyq, btype="low", output="sos")
return apply_sos(audio, sos)
def highpass(audio: np.ndarray, cutoff: float, order: int = 3) -> np.ndarray:
cutoff = clamp_freq(cutoff)
nyq = SAMPLE_RATE / 2.0
if cutoff <= 20.0:
return audio
sos = butter(order, cutoff / nyq, btype="high", output="sos")
return apply_sos(audio, sos)
def bandpass(audio: np.ndarray, low: float, high: float, order: int = 2) -> np.ndarray:
nyq = SAMPLE_RATE / 2.0
low = max(20.0, min(low, nyq - 100.0))
high = max(20.0, min(high, nyq - 100.0))
if high <= low:
high = min(nyq - 100.0, low * 1.1)
if high <= low:
return audio
sos = butter(order, [low / nyq, high / nyq], btype="band", output="sos")
return apply_sos(audio, sos)
def mix(layers: List[Tuple[np.ndarray, float]]) -> np.ndarray:
max_len = max((len(a) for a, _ in layers if a is not None), default=0)
out = np.zeros(max_len, dtype=np.float64)
for audio, gain in layers:
if audio is None or gain == 0.0:
continue
out[: len(audio)] += np.asarray(audio, dtype=np.float64) * float(gain)
return out
def add_delayed(base: np.ndarray, layer: np.ndarray, delay_s: float, gain: float = 1.0) -> np.ndarray:
delay = int(round(delay_s * SAMPLE_RATE))
needed = max(len(base), delay + len(layer))
out = np.zeros(needed, dtype=np.float64)
out[: len(base)] += base
out[delay : delay + len(layer)] += layer * float(gain)
return out
def concat(arrays: List[np.ndarray], gap_s: float = 0.0) -> np.ndarray:
if not arrays:
return np.zeros(1, dtype=np.float64)
gap_len = max(0, int(round(gap_s * SAMPLE_RATE)))
gap = np.zeros(gap_len, dtype=np.float64)
parts: List[np.ndarray] = []
for i, array in enumerate(arrays):
parts.append(array)
if i != len(arrays) - 1 and gap_len > 0:
parts.append(gap)
return np.concatenate(parts)
def tone(
duration: float,
f0: float,
f1: float | None = None,
wave: str = "sine",
curve: str = "exp",
vibrato_hz: float = 0.0,
vibrato_depth: float = 0.0,
) -> np.ndarray:
n = max(1, int(round(duration * SAMPLE_RATE)))
t = np.arange(n, dtype=np.float64) / SAMPLE_RATE
if f1 is None:
freqs = np.full(n, float(f0), dtype=np.float64)
else:
if curve == "exp" and f0 > 0 and f1 > 0:
freqs = float(f0) * (float(f1) / float(f0)) ** (t / max(duration, 1e-6))
else:
freqs = np.linspace(float(f0), float(f1), n)
if vibrato_depth > 0 and vibrato_hz > 0:
freqs = freqs * (1.0 + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t))
phase = 2.0 * np.pi * np.cumsum(freqs) / SAMPLE_RATE
if wave == "sine":
y = np.sin(phase)
elif wave == "square":
y = np.sign(np.sin(phase))
elif wave == "triangle":
y = (2.0 / np.pi) * np.arcsin(np.sin(phase))
elif wave == "saw":
y = 2.0 * (phase / (2.0 * np.pi) - np.floor(0.5 + phase / (2.0 * np.pi)))
else:
y = np.sin(phase)
return y
def ev(arrays: List[np.ndarray], mode: str | None = None, volume: float = 1.0) -> Dict:
if mode is None:
mode = "single" if len(arrays) == 1 else "random"
return {
"arrays": arrays,
"mode": mode,
"volume": float(volume),
}
def chip_blip(
duration: float,
f0: float,
f1: float | None = None,
target_db: float = -3.0,
) -> np.ndarray:
y = tone(duration, f0, f1, wave="square", curve="linear")
y *= decay_env(duration, duration / 3.0, attack_s=0.0003)
y = lowpass(y, 9500.0)
return finalize(y, target_db=target_db)
def chip_sequence(
notes: List[Tuple[float, float]],
note_dur: float = 0.045,
gap: float = 0.002,
) -> np.ndarray:
parts = [chip_blip(note_dur, f0, f1) for f0, f1 in notes]
return finalize(concat(parts, gap_s=gap))
def bubble(
rng: np.random.Generator,
duration: float,
f0: float,
f1: float,
low: float = 300.0,
high: float = 2600.0,
pop_gain: float = 0.28,
) -> np.ndarray:
y = tone(duration, f0, f1, wave="sine", curve="exp")
y *= decay_env(duration, duration / 3.2)
y = bandpass(y, low, high)
pop_dur = min(0.009, duration * 0.25)
pop = noise(rng, pop_dur)
pop = lowpass(pop, 1800.0)
pop *= decay_env(pop_dur, 0.003)
y = mix([(y, 0.92), (pop, pop_gain)])
y = highpass(y, 70.0)
y = lowpass(y, 9000.0)
return finalize(y)
def build_chiptune_arcade(rng: np.random.Generator) -> Dict[str, Dict]:
def default_variant(i: int) -> np.ndarray:
r = child_rng(rng, 10 + i)
f0 = float(r.choice([784.0, 880.0, 987.0, 1046.0]))
return chip_blip(0.045, f0, f0 * 0.82)
space = chip_blip(0.080, 300.0, 940.0)
delete = chip_blip(0.070, 950.0, 220.0)
ret = chip_sequence(
[(659.0, 659.0), (880.0, 880.0), (1318.0, 1318.0)],
note_dur=0.042,
gap=0.003,
)
shift = chip_blip(0.038, 1318.0, 1760.0)
symbol = chip_sequence(
[(987.0, 987.0), (1318.0, 1318.0)],
note_dur=0.036,
gap=0.004,
)
return {
"keypress.default": ev([default_variant(i) for i in range(3)], "random", 1.0),
"keypress.space": ev([space], "single", 1.0),
"keypress.delete": ev([delete], "single", 0.95),
"keypress.return": ev([ret], "single", 0.95),
"keypress.shift": ev([shift], "single", 0.90),
"keypress.symbol": ev([symbol], "single", 0.90),
}
def build_ceramic_glass_marble(rng: np.random.Generator) -> Dict[str, Dict]:
def glass_hit(r, duration, base):
return _ac_modal(
duration,
base,
ratios=[1.0, 2.68, 4.05, 5.82],
gains=[0.8, 0.35, 0.22, 0.12],
taus=[duration / 3.0, duration / 4.0, duration / 5.0, duration / 6.0],
rng=r,
)
def default_variant(i: int) -> np.ndarray:
r = child_rng(rng, 10 + i)
base = float(r.uniform(2100.0, 2700.0))
return finalize(glass_hit(r, float(r.uniform(0.038, 0.048)), base))
space = finalize(glass_hit(child_rng(rng, 20), 0.070, 1200.0))
delete = finalize(glass_hit(child_rng(rng, 21), 0.035, 2600.0))
ret = finalize(glass_hit(child_rng(rng, 22), 0.090, 1800.0))
shift = finalize(glass_hit(child_rng(rng, 23), 0.035, 2900.0))
symbol = finalize(concat([glass_hit(child_rng(rng, 24), 0.040, 2300.0), glass_hit(child_rng(rng, 25), 0.040, 2800.0)], gap_s=0.010))
return {
"keypress.default": ev([default_variant(i) for i in range(3)], "random", 1.0),
"keypress.space": ev([space], "single", 1.0),
"keypress.delete": ev([delete], "single", 0.95),
"keypress.return": ev([ret], "single", 0.95),
"keypress.shift": ev([shift], "single", 0.90),
"keypress.symbol": ev([symbol], "single", 0.90),
}
def build_water_bubble_pop(rng: np.random.Generator) -> Dict[str, Dict]:
def default_variant(i: int) -> np.ndarray:
r = child_rng(rng, 10 + i)
f0 = float(r.uniform(950.0, 1400.0))
f1 = f0 * float(r.uniform(0.32, 0.45))
return bubble(r, float(r.uniform(0.045, 0.060)), f0, f1)
space = bubble(child_rng(rng, 20), 0.100, 320.0, 110.0, low=120.0, high=900.0)
delete = bubble(child_rng(rng, 21), 0.040, 1600.0, 700.0, low=400.0, high=3200.0)
ret = finalize(concat([bubble(child_rng(rng, 22), 0.055, 700.0, 350.0), bubble(child_rng(rng, 23), 0.055, 1000.0, 450.0)], gap_s=0.008))
shift = bubble(child_rng(rng, 24), 0.035, 1800.0, 900.0)
symbol = finalize(concat([bubble(child_rng(rng, 25), 0.040, 1200.0, 600.0), bubble(child_rng(rng, 26), 0.035, 1500.0, 800.0)], gap_s=0.007))
return {
"keypress.default": ev([default_variant(i) for i in range(3)], "random", 1.0),
"keypress.space": ev([space], "single", 1.0),
"keypress.delete": ev([delete], "single", 0.95),
"keypress.return": ev([ret], "single", 0.95),
"keypress.shift": ev([shift], "single", 0.90),
"keypress.symbol": ev([symbol], "single", 0.90),
}
# ----------------------------------------------------------------------------
# LeanType Ultra-Realistic Procedural Sound Pack Engine
# Drop-in physical-modeling helpers + upgraded builder functions
# ----------------------------------------------------------------------------
#
# This file assumes the following primitives already exist in
# tools/generate_all_soundpacks.py:
#
# SAMPLE_RATE
# finalize(...)
# tone(...)
# decay_env(...)
# noise(...)
# lowpass(...)
# highpass(...)
# bandpass(...)
# mix(...)
# add_delayed(...)
# concat(...)
# ev(...)
# child_rng(...)
#
# All new helpers are prefixed with _ac_ to avoid collisions.
# ----------------------------------------------------------------------------
def _ac_final(audio: np.ndarray) -> np.ndarray:
"""
Compatibility wrapper for final normalization.
"""
try:
return finalize(
audio,
target_db=-2.0,
fade_in_ms=0.3,
fade_out_ms=2.0,
)
except TypeError:
return finalize(audio, target_db=-2.0)
def _ac_brown_noise(rng: np.random.Generator, duration: float) -> np.ndarray:
"""
Brownian noise: integrated white noise.
Much more organic than raw white noise for friction, air movement,
wooden bodies, drum shells, and cavity resonance excitation.
"""
n = max(1, int(round(duration * SAMPLE_RATE)))
x = np.cumsum(rng.standard_normal(n))
x -= float(np.mean(x))
peak = float(np.max(np.abs(x)))
if peak > 1e-9:
x /= peak
return x
def _ac_softsat(audio: np.ndarray, drive: float = 2.0) -> np.ndarray:
"""
Gentle tanh soft saturation.
Used to turn mathematically clean waveforms into non-linear physical
collision material. This adds dense, organic harmonics without the
brittle character of bare sine waves.
"""
audio = np.asarray(audio, dtype=np.float64)
if audio.size == 0 or drive <= 0.0:
return audio
y = np.tanh(drive * audio)
peak = float(np.max(np.abs(y)))
if peak > 1e-9:
y /= peak
return y
def _ac_delayed_decay(
duration: float,
delay_s: float,
tau: float,
attack_s: float = 0.0002,
) -> np.ndarray:
"""
Creates an exponential decay envelope that starts after delay_s.
This is used for multi-stage physical events:
0.0 ms : initial impact
2.0 ms : body displacement
4.0 ms+ : cavity / resonant decay
"""
n = max(1, int(round(duration * SAMPLE_RATE)))
env = np.zeros(n, dtype=np.float64)
start = int(round(delay_s * SAMPLE_RATE))
if start >= n:
return env
seg_dur = (n - start) / SAMPLE_RATE
seg = decay_env(seg_dur, max(0.001, tau), attack_s=attack_s)
if len(seg) > n - start:
seg = seg[: n - start]
env[start:] = seg
return env
def _ac_fm_impact(
rng: np.random.Generator,
duration: float,
f0: float,
f1: float,
mod_ratio: float = 1.8,
index0: float = 6.0,
drive: float = 2.5,
) -> np.ndarray:
"""
Non-linear collision impulse using fast exponential FM pitch sweep.
Bare sine waves are avoided. Instead:
- exponentially falling/rising carrier frequency
- decaying FM index
- small noise injection
- tanh saturation
This creates a dense physical contact transient.
"""
n = max(1, int(round(duration * SAMPLE_RATE)))
t = np.arange(n, dtype=np.float64) / SAMPLE_RATE
f0 = max(20.0, float(f0))
f1 = max(20.0, float(f1))
ratio = max(f1 / f0, 1e-6)
freqs = f0 * (ratio ** (t / max(duration, 1e-5)))
carrier_phase = 2.0 * np.pi * np.cumsum(freqs) / SAMPLE_RATE
mod_freqs = freqs * float(mod_ratio)
mod_phase = 2.0 * np.pi * np.cumsum(mod_freqs) / SAMPLE_RATE
mod_env = np.exp(-t / max(duration / 6.0, 0.001))
y = np.sin(carrier_phase + float(index0) * mod_env * np.sin(mod_phase))
# Tiny stochastic component prevents sterile mathematical repetition.
y += 0.10 * rng.standard_normal(n)
return _ac_softsat(y, drive)
def _ac_noise_burst(
rng: np.random.Generator,
duration: float,
low: float | None = None,
high: float | None = None,
drive: float = 2.0,
) -> np.ndarray:
"""
Coloured friction noise burst.
Uses brownian noise blended with a small amount of white noise, then
filters and soft-saturates it. This avoids harsh synthetic white-noise
clicks while still preserving physical contact detail.
"""
brown = _ac_brown_noise(rng, duration)
white = noise(rng, duration)
x = 0.72 * brown + 0.28 * white
x = lowpass(x, min(14000.0, SAMPLE_RATE / 2.0 - 500.0))
nyq_limit = SAMPLE_RATE / 2.0 - 200.0
if low is not None and high is not None:
low = max(30.0, float(low))
high = min(float(high), nyq_limit)
if high <= low:
high = min(nyq_limit, low * 1.1)
if high > low:
x = bandpass(x, low, high, order=2)
elif high is not None:
high = min(float(high), nyq_limit)
x = highpass(x, high)
elif low is not None:
low = max(30.0, float(low))
x = highpass(x, low)
x *= decay_env(duration, max(0.0015, duration / 5.0), attack_s=0.0002)
return _ac_softsat(x, drive)
def _ac_cavity(
rng: np.random.Generator,
duration: float,
bands: List[Tuple[float, float, float]],
drive: float = 1.4,
) -> np.ndarray:
"""
Hollow-body / Helmholtz cavity model.
Each band is:
(center_frequency, bandwidth, gain)
The cavity is excited by coloured noise and rendered with parallel
resonant bandpass filters plus weak sine resonators.
"""
n = max(1, int(round(duration * SAMPLE_RATE)))
out = np.zeros(n, dtype=np.float64)
src = _ac_noise_burst(rng, duration, drive=1.2)
for freq, bw, gain in bands:
freq = float(freq) * float(rng.uniform(0.980, 1.020))
bw = max(15.0, float(bw))
lo = max(30.0, freq - bw * 0.5)
hi = min(SAMPLE_RATE / 2.0 - 200.0, freq + bw * 0.5)
if hi <= lo:
continue
bp = bandpass(src, lo, hi, order=2)
ring = tone(duration, freq, freq * 0.992, wave="sine", curve="exp")
ring *= decay_env(duration, max(0.006, duration / 5.0), attack_s=0.0003)
out += bp * float(gain)
out += ring * float(gain) * 0.22
return _ac_softsat(out, drive)
def _ac_modal(
duration: float,
base_freq: float,
ratios: List[float],
gains: List[float],
taus: float | List[float],
rng: np.random.Generator | None = None,
detune: float = 0.004,
) -> np.ndarray:
"""
Multi-modal resonance builder.
Used for membranes, tines, bells, strings, wooden bodies, and metal parts.
"""
if isinstance(taus, (int, float)):
taus = [float(taus)] * len(ratios)
else:
taus = [float(t) for t in taus]
while len(taus) < len(ratios):
taus.append(taus[-1])
layers: List[Tuple[np.ndarray, float]] = []
for ratio, gain, tau in zip(ratios, gains, taus):
freq = float(base_freq) * float(ratio)
if rng is not None and detune > 0.0:
freq *= float(rng.uniform(1.0 - detune, 1.0 + detune))
partial = tone(duration, freq, freq * 0.995, wave="sine", curve="exp")
partial *= decay_env(duration, max(0.001, tau), attack_s=0.00025)
layers.append((partial, float(gain)))
return mix(layers)
def _ac_switch_hit(
rng: np.random.Generator,
duration: float,
bottom: float = 150.0,
cavity_bands: List[Tuple[float, float, float]] | None = None,
click_low: float = 3800.0,
click_high: float = 5500.0,
click_gain: float = 0.45,
bottom_gain: float = 0.85,
spring_freq: float = 1800.0,
spring_gain: float = 0.07,
drive: float = 2.6,
lowpass_cutoff: float = 9000.0,
highpass_cutoff: float = 45.0,
second_click_delay: float = 0.0,
second_click_gain: float = 0.0,
) -> np.ndarray:
"""
Multi-stage mechanical switch physics.
Stage 1: 0-2 ms high-frequency impact / click-bar snap.
Stage 2: 2-12 ms low-mid body displacement / bottom-out.
Stage 3: 4+ ms cavity decay and subtle spring/metal ring.
"""
if cavity_bands is None:
cavity_bands = [
(260.0, 90.0, 0.65),
(460.0, 130.0, 0.42),
]
layers: List[Tuple[np.ndarray, float]] = []
# ------------------------------------------------------------------
# Stage 1: primary impact transient
# ------------------------------------------------------------------
click_fm = _ac_fm_impact(
rng,
duration,
click_high * 0.95,
click_low * 0.75,
mod_ratio=2.1,
index0=5.5,
drive=drive * 0.75,
)
click_noise = _ac_noise_burst(
rng,
duration,
low=click_low,
high=click_high,
drive=drive * 0.65,
)
click_env = _ac_delayed_decay(duration, 0.0, 0.0032, attack_s=0.00015)
click = mix(
[
(click_fm, 0.75),
(click_noise, click_gain),
]
) * click_env
layers.append((click, 1.0))
# ------------------------------------------------------------------
# Optional secondary click: tactile snap, double click, housing impact
# ------------------------------------------------------------------
if second_click_gain > 0.0:
r2 = child_rng(rng, 91)
click2_fm = _ac_fm_impact(
r2,
duration,
click_high * 0.82,
click_low * 0.68,
mod_ratio=2.0,
index0=4.6,
drive=drive * 0.70,
)
click2_noise = _ac_noise_burst(
r2,
duration,
low=click_low * 0.90,
high=click_high * 0.90,
drive=drive * 0.60,
)
click2_env = _ac_delayed_decay(
duration,
second_click_delay,
0.0036,
attack_s=0.00015,
)
click2 = mix(
[
(click2_fm, 0.68),
(click2_noise, click_gain * 0.90),
]
) * click2_env * float(second_click_gain)
layers.append((click2, 1.0))
# ------------------------------------------------------------------
# Stage 2: body displacement / bottom-out impact
# ------------------------------------------------------------------
bottom_fm = _ac_fm_impact(
rng,
duration,
bottom * 2.4,
bottom * 0.82,
mod_ratio=1.35,
index0=4.8,
drive=drive,
)
bottom_noise = _ac_noise_burst(
rng,
duration,
low=bottom * 0.8,
high=bottom * 4.0,
drive=drive * 0.55,
)
bottom_env = _ac_delayed_decay(
duration,
0.002,
max(0.006, duration / 7.5),
attack_s=0.0002,
)
bottom = mix(
[
(bottom_fm, 0.80),
(bottom_noise, 0.40),
]
) * bottom_env * float(bottom_gain)
layers.append((bottom, 1.0))
# ------------------------------------------------------------------
# Stage 3: cavity decay
# ------------------------------------------------------------------
cavity = _ac_cavity(rng, duration, cavity_bands, drive=drive * 0.55)
cavity_env = _ac_delayed_decay(
duration,
0.004,
max(0.014, duration / 3.8),
attack_s=0.0003,
)
layers.append((cavity * cavity_env, 0.90))
# ------------------------------------------------------------------
# Subtle spring / metallic after-ring
# ------------------------------------------------------------------
if spring_gain > 0.0:
spring_f = float(spring_freq) * float(rng.uniform(0.980, 1.020))
spring = tone(duration, spring_f, spring_f * 0.985, wave="sine", curve="exp")
spring *= _ac_delayed_decay(
duration,
0.007,
max(0.008, duration / 7.0),
attack_s=0.0003,
)
layers.append((spring, float(spring_gain)))
# ------------------------------------------------------------------
# Air / friction tail
# ------------------------------------------------------------------
air = lowpass(_ac_brown_noise(rng, duration), 900.0)
air *= _ac_delayed_decay(
duration,
0.006,
max(0.010, duration / 5.0),
attack_s=0.0003,
)
air *= 0.07
layers.append((air, 1.0))
y = mix(layers)
if highpass_cutoff > 0.0:
y = highpass(y, highpass_cutoff)
if lowpass_cutoff > 0.0:
y = lowpass(y, min(lowpass_cutoff, SAMPLE_RATE / 2.0 - 300.0))
y = _ac_softsat(y, max(1.1, drive * 0.35))
return _ac_final(y)
def _ac_modal_instrument(
rng: np.random.Generator,
duration: float,
base: float,
ratios: List[float],
gains: List[float],
taus: List[float],
exciter_low: float,
exciter_high: float,
exciter_gain: float = 0.55,
body_bands: List[Tuple[float, float, float]] | None = None,
body_gain: float = 0.45,
drive: float = 2.2,
lowpass_cutoff: float = 10000.0,
highpass_cutoff: float = 50.0,
) -> np.ndarray:
"""
Generic resonant acoustic object:
- modal resonators
- physical impact exciter
- hollow-body cavity
- friction tail
"""
if body_bands is None:
body_bands = [
(300.0, 100.0, 0.50),
(650.0, 180.0, 0.30),
]
modal = _ac_modal(
duration,
base,
ratios,
gains,
taus,
rng=rng,
detune=0.003,
)
impact_fm = _ac_fm_impact(
rng,
duration,
exciter_high,
exciter_low * 0.8,
mod_ratio=2.2,
index0=5.2,
drive=drive * 0.80,
)
impact_noise = _ac_noise_burst(
rng,
duration,
low=exciter_low,
high=exciter_high,
drive=drive * 0.70,
)
exciter = mix(
[
(impact_fm, 0.70),
(impact_noise, exciter_gain),
]
) * _ac_delayed_decay(duration, 0.0, 0.004, attack_s=0.00015)
cavity = _ac_cavity(rng, duration, body_bands, drive=drive * 0.55)
cavity *= _ac_delayed_decay(
duration,
0.003,
max(0.012, duration / 3.5),
attack_s=0.0003,
)
cavity *= float(body_gain)
friction = lowpass(_ac_brown_noise(rng, duration), 1200.0)
friction *= _ac_delayed_decay(
duration,
0.005,
max(0.010, duration / 5.0),
attack_s=0.0003,
)
friction *= 0.08
y = mix(
[
(modal, 0.88),
(exciter, 1.0),
(cavity, 1.0),
(friction, 1.0),
]
)
if highpass_cutoff > 0.0:
y = highpass(y, highpass_cutoff)
if lowpass_cutoff > 0.0:
y = lowpass(y, min(lowpass_cutoff, SAMPLE_RATE / 2.0 - 300.0))
y = _ac_softsat(y, max(1.2, drive * 0.35))
return _ac_final(y)
def _ac_ks_pluck(
rng: np.random.Generator,
freq: float,
duration: float,
brightness: float = 0.5,
damping: float | None = None,
dispersion: float = 0.20,
) -> np.ndarray:
"""
Karplus-Strong plucked string with a simple first-order dispersion allpass.
The allpass adds subtle phase dispersion, making nylon/string attacks less
"delay-line synthetic" and more physically flexible.
"""
freq = max(20.0, float(freq))
brightness = float(np.clip(brightness, 0.0, 1.0))
n_out = max(1, int(round(duration * SAMPLE_RATE)))
period = max(2, int(round(SAMPLE_RATE / freq)))
# Initial excitation: low-smoothed noise burst.
buf = rng.uniform(-1.0, 1.0, period)
for _ in range(2):
buf = 0.5 * (buf + np.roll(buf, 1))
if damping is None:
damping = 0.986 + 0.012 * brightness
damping = float(np.clip(damping, 0.970, 0.999))
a = float(np.clip(dispersion, 0.0, 0.55))
out = np.empty(n_out, dtype=np.float64)
idx = 0
prev_x = 0.0
prev_y = 0.0
for i in range(n_out):