sonicase commited on
Commit
90f6d15
·
1 Parent(s): 8e35f78

new rain simulation method

Browse files
Files changed (3) hide show
  1. README.md +7 -3
  2. app.py +412 -406
  3. requirements.txt +1 -0
README.md CHANGED
@@ -10,15 +10,19 @@ pinned: false
10
  license: mit
11
  ---
12
 
13
- # Granular Synthesis — Interactive Demo
14
 
15
  Educational demo of granular synthesis with two modes.
16
 
17
  ## Rain Simulation
18
 
19
- Each raindrop is a procedurally generated grain: noise burst → biquad low-pass filter → exponential envelope. Thousands of grains, scattered randomly in time with per-drop variation in size, spectral content, amplitude, and stereo position, create realistic rain textures.
 
 
 
20
 
21
- Three layers: individual drops (granular scatter), continuous wash (filtered brownian noise), and optional thunder (low-frequency sine cluster).
 
22
 
23
  ## Tonal Granular
24
 
 
10
  license: mit
11
  ---
12
 
13
+ # Granular Synthesis
14
 
15
  Educational demo of granular synthesis with two modes.
16
 
17
  ## Rain Simulation
18
 
19
+ Spectral-domain rain synthesis. White noise is sculpted in the frequency domain
20
+ to match the spectral profile of real rainfall (energy concentrated 2 to 12 kHz,
21
+ with slope varying by intensity). Each STFT frame is a "grain" whose spectrum
22
+ is shaped by the rain profile, then overlap-added into the output.
23
 
24
+ Three layers: continuous spectral wash, sparse transient drops (scipy bandpass filtered),
25
+ and optional thunder rumble.
26
 
27
  ## Tonal Granular
28
 
app.py CHANGED
@@ -1,287 +1,369 @@
1
  """
2
- Granular Synthesis Demo Rain Simulation (v2)
3
- ===============================================
4
- v2 fixes the "frying bacon" problem:
5
- - Biquad low-pass filter instead of naive box averaging
6
- - Resonant body model for each drop (drops ring, not just click)
7
- - Longer grains with proper exponential-then-silence tail
8
- - Stereo field with per-drop panning
9
- - Layered background wash using filtered brownian noise
10
-
11
- The core granular principle is the same: thousands of tiny
12
- overlapping sound fragments emergent texture.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  """
14
 
15
  import numpy as np
 
 
16
  import gradio as gr
17
 
18
  # ---------------------------------------------------------------------------
19
  # Constants
20
  # ---------------------------------------------------------------------------
21
  SR = 44100
22
- DURATION = 6.0 # output length in seconds
23
 
24
  # ---------------------------------------------------------------------------
25
- # DSP utilities
26
  # ---------------------------------------------------------------------------
27
 
28
- def biquad_lowpass(signal: np.ndarray, cutoff_hz: float, sr: int = SR, Q: float = 0.707) -> np.ndarray:
 
 
 
 
29
  """
30
- Second-order IIR low-pass filter (biquad).
 
31
 
32
- WHY a biquad instead of moving-average?
33
- A moving average is a very weak filter it barely attenuates
34
- high frequencies and creates comb-filter artifacts.
35
- A biquad gives a proper -12 dB/octave roll-off with a tunable
36
- cutoff frequency, which is essential for shaping rain timbre.
37
 
38
- The math comes from the Audio EQ Cookbook (Robert Bristow-Johnson).
 
39
  """
40
- w0 = 2.0 * np.pi * cutoff_hz / sr
41
- alpha = np.sin(w0) / (2.0 * Q)
42
-
43
- b0 = (1.0 - np.cos(w0)) / 2.0
44
- b1 = 1.0 - np.cos(w0)
45
- b2 = b0
46
- a0 = 1.0 + alpha
47
- a1 = -2.0 * np.cos(w0)
48
- a2 = 1.0 - alpha
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  # Normalize
51
- b = np.array([b0 / a0, b1 / a0, b2 / a0])
52
- a = np.array([1.0, a1 / a0, a2 / a0])
53
-
54
- # Apply filter (direct form II transposed)
55
- out = np.zeros_like(signal)
56
- z1, z2 = 0.0, 0.0
57
- for i in range(len(signal)):
58
- x = signal[i]
59
- y = b[0] * x + z1
60
- z1 = b[1] * x - a[1] * y + z2
61
- z2 = b[2] * x - a[2] * y
62
- out[i] = y
63
- return out
64
-
65
-
66
- def brownian_noise(n_samples: int) -> np.ndarray:
67
- """
68
- Brownian (red) noise = integrated white noise.
69
 
70
- WHY brownian? It has a -6 dB/octave spectral slope, which sounds
71
- like a deep, smooth rumble — much closer to steady rain wash
72
- than white noise (which sounds like static/frying).
73
- """
74
- white = np.random.randn(n_samples) * 0.02
75
- brown = np.cumsum(white)
76
- # Remove DC drift and normalize
77
- brown -= np.mean(brown)
78
- peak = np.max(np.abs(brown))
79
- if peak > 0:
80
- brown /= peak
81
- return brown
82
 
83
 
84
  # ---------------------------------------------------------------------------
85
- # Raindrop grain synthesis (v2 much better)
86
  # ---------------------------------------------------------------------------
87
 
88
- def make_raindrop(
89
- size_ms: float,
90
- cutoff_hz: float,
91
- resonance: float = 1.0,
92
- ) -> np.ndarray:
93
  """
94
- Synthesize one raindrop as: noise burst biquad filter → envelope.
95
-
96
- A real raindrop sound has three phases:
97
- 1. IMPACT — very short broadband transient (< 1 ms)
98
- 2. BODY — the surface resonates briefly (metal rings, glass taps)
99
- 3. TAIL — fast exponential decay into silence
100
 
101
- We model this with a noise burst shaped by:
102
- - A two-stage envelope (sharp attack + tunable decay)
103
- - A biquad low-pass at a cutoff that varies with drop "size"
104
- - Resonance (Q factor) that models the surface material
105
  """
106
- n = max(int((size_ms / 1000.0) * SR), 64)
107
- t = np.linspace(0, 1, n, endpoint=False)
108
-
109
- # --- Two-stage envelope: fast attack, variable decay ---
110
- # The attack is near-instant (first 5% of grain).
111
- # The decay rate determines how "ringy" vs "dead" the surface is.
112
- attack = np.minimum(t / 0.02, 1.0) # ramp up in first 2% of grain
113
- decay = np.exp(-6.0 * t) # smooth exponential tail
114
- envelope = attack * decay
115
-
116
- # --- Noise source ---
117
- # WHY noise and not a sine? Water impact is chaotic — it excites
118
- # all frequencies at once. The filter then shapes the spectrum.
119
- noise = np.random.randn(n)
120
-
121
- # --- Apply envelope BEFORE filtering ---
122
- # This way the filter's transient response adds a natural "ring"
123
- # to the attack, which sounds like a surface being excited.
124
- shaped = noise * envelope
125
-
126
- # --- Biquad low-pass with resonance ---
127
- # cutoff_hz controls brightness (glass=high, soil=low)
128
- # resonance (Q) controls how much the surface "rings"
129
- Q = 0.707 + resonance * 2.0 # 0.707=flat, higher=resonant peak
130
- filtered = biquad_lowpass(shaped, cutoff_hz, Q=Q)
131
-
132
- # Normalize grain
133
- peak = np.max(np.abs(filtered))
134
- if peak > 0:
135
- filtered /= peak
136
 
137
- return filtered
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
 
140
  # ---------------------------------------------------------------------------
141
- # Rain engine (v2)
142
  # ---------------------------------------------------------------------------
143
 
144
  def synthesize_rain(
145
  rain_type: str,
146
- drop_size_ms: float,
147
- drops_per_sec: float,
148
- intensity: float,
149
- surface_brightness: float,
150
- surface_resonance: float,
151
  stereo_width: float,
 
 
152
  ) -> np.ndarray:
153
  """
154
- Full rain synthesis engine.
155
-
156
- Architecture:
157
- Layer 1 — Individual drops (granular scatter)
158
- Layer 2 — Continuous wash (filtered brownian noise)
159
- Layer 3 — Thunder rumble (optional, low sine cluster)
160
 
161
- Each layer uses different granular/procedural techniques
162
- but they combine into a cohesive, natural rain sound.
 
163
  """
164
  n_out = int(DURATION * SR)
165
- # Stereo output: shape (n_out, 2)
166
- output = np.zeros((n_out, 2), dtype=np.float64)
167
-
168
- # --- Map surface_brightness (0–1) to filter cutoff ---
169
- # 0 = very dark (soil, 400 Hz) → 1 = very bright (tin, 8000 Hz)
170
- # WHY logarithmic mapping? Human pitch perception is logarithmic.
171
- cutoff = 400.0 * (2.0 ** (surface_brightness * 4.3)) # 400 → ~8000 Hz
172
-
173
- # --- Rain type presets modify the base parameters ---
174
- type_config = {
175
- "light": {"density_mult": 0.4, "size_mult": 0.6, "wash": 0.0, "thunder": False},
176
- "medium": {"density_mult": 1.0, "size_mult": 1.0, "wash": 0.08, "thunder": False},
177
- "heavy": {"density_mult": 2.5, "size_mult": 1.4, "wash": 0.25, "thunder": False},
178
- "thunder": {"density_mult": 3.0, "size_mult": 1.6, "wash": 0.35, "thunder": True},
179
- }
180
- cfg = type_config.get(rain_type, type_config["medium"])
181
-
182
- total_drops = int(drops_per_sec * cfg["density_mult"] * intensity * DURATION)
183
- actual_size = drop_size_ms * cfg["size_mult"]
184
-
185
- # --- LAYER 1: Individual raindrop grains ---
186
- # Poisson-random placement in time (real rain is stochastic)
187
- drop_times = np.random.randint(0, max(n_out - int(actual_size / 1000 * SR) - 1, 1), size=total_drops)
188
-
189
- for pos in drop_times:
190
- # Per-drop variation (no two drops identical)
191
- this_size = actual_size * np.random.uniform(0.5, 1.8)
192
- this_cutoff = cutoff * np.random.uniform(0.6, 1.5)
193
- this_res = surface_resonance * np.random.uniform(0.3, 1.0)
194
-
195
- grain = make_raindrop(this_size, this_cutoff, this_res)
196
- g_len = len(grain)
197
-
198
- end = min(pos + g_len, n_out)
199
- actual = end - pos
200
-
201
- # Amplitude: random distance simulation (far drops are quieter)
202
- amp = np.random.uniform(0.15, 1.0) ** 1.5 # power curve = more quiet drops
203
-
204
- # Stereo panning: random position in the stereo field
205
- # pan=0 → full left, pan=1 → full right
206
- pan = 0.5 + (np.random.uniform(-1, 1) * stereo_width * 0.5)
207
- pan = np.clip(pan, 0, 1)
208
-
209
- # Constant-power panning (preserves perceived loudness)
210
- L = np.cos(pan * np.pi / 2) * amp
211
- R = np.sin(pan * np.pi / 2) * amp
212
-
213
- output[pos:end, 0] += grain[:actual] * L
214
- output[pos:end, 1] += grain[:actual] * R
215
-
216
- # --- LAYER 2: Continuous background wash ---
217
- # WHY a separate layer? When thousands of tiny drops overlap,
218
- # you stop hearing individuals — it becomes a continuous "shhh".
219
- # We model this directly with filtered brownian noise.
220
- if cfg["wash"] > 0:
221
- wash_L = brownian_noise(n_out)
222
- wash_R = brownian_noise(n_out) # independent channels = spatial width
223
-
224
- # Filter the wash to match the surface brightness
225
- wash_cutoff = cutoff * 0.6 # wash is always darker than individual drops
226
- wash_L = biquad_lowpass(wash_L, wash_cutoff)
227
- wash_R = biquad_lowpass(wash_R, wash_cutoff)
228
-
229
- # Slow amplitude modulation — rain wash isn't perfectly steady
230
- t = np.linspace(0, DURATION, n_out)
231
- mod = 0.7 + 0.3 * np.sin(2 * np.pi * 0.15 * t + np.random.uniform(0, 2 * np.pi))
232
-
233
- output[:, 0] += wash_L * mod * cfg["wash"] * intensity
234
- output[:, 1] += wash_R * mod * cfg["wash"] * intensity
235
-
236
- # --- LAYER 3: Thunder ---
237
- if cfg["thunder"]:
238
- n_thunders = np.random.randint(1, 3)
239
- for _ in range(n_thunders):
240
- th_pos = np.random.randint(0, n_out // 2)
241
- th_len = int(SR * np.random.uniform(1.5, 3.5))
242
- t = np.linspace(0, 1, th_len)
243
-
244
- rumble = np.zeros(th_len)
245
- for f in [22, 35, 48, 65, 80]:
246
- phase = np.random.uniform(0, 2 * np.pi)
247
- rumble += np.sin(2 * np.pi * f * t + phase) * np.random.uniform(0.3, 1.0)
248
-
249
- # Thunder envelope: slow build, long tail
250
- env = np.exp(-1.2 * t) * (1 - np.exp(-8 * t))
251
- rumble *= env * 0.35
252
-
253
- end = min(th_pos + th_len, n_out)
254
- seg = rumble[:end - th_pos]
255
- # Thunder is roughly centered in stereo
256
- output[th_pos:end, 0] += seg * 0.8
257
- output[th_pos:end, 1] += seg * 0.8
258
-
259
- # --- Final normalization ---
260
- peak = np.max(np.abs(output))
261
  if peak > 0:
262
- output *= 0.9 / peak
263
 
264
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
 
266
 
267
  # ---------------------------------------------------------------------------
268
- # Tonal granular engine (unchanged logic, improved quality)
269
  # ---------------------------------------------------------------------------
270
 
271
  def make_tonal_source(freq: float = 220.0, duration: float = 2.0) -> np.ndarray:
272
  t = np.linspace(0, duration, int(SR * duration), endpoint=False)
273
- signal = np.zeros_like(t)
274
  for k in range(1, 8):
275
- signal += (1.0 / k) * np.sin(2 * np.pi * freq * k * t)
276
- signal /= np.max(np.abs(signal))
277
- return signal
278
 
279
 
280
  def granular_synthesize(source, grain_size_ms, density, randomness, pitch_shift):
281
  grain_samples = max(int((grain_size_ms / 1000.0) * SR), 64)
282
  window = np.hanning(grain_samples)
283
  hop = max(int(grain_samples / density), 1)
284
-
285
  n_out = int(DURATION * SR)
286
  output = np.zeros(n_out, dtype=np.float64)
287
 
@@ -302,7 +384,6 @@ def granular_synthesize(source, grain_size_ms, density, randomness, pitch_shift)
302
  rand_pos = np.random.randint(0, max(src_len - grain_samples, 1))
303
  start = int(seq_pos * (1 - randomness) + rand_pos * randomness)
304
  start = np.clip(start, 0, src_len - grain_samples)
305
-
306
  grain = pitched[start: start + grain_samples] * window
307
  out_pos = i * hop
308
  if out_pos + grain_samples > n_out:
@@ -317,11 +398,11 @@ def granular_synthesize(source, grain_size_ms, density, randomness, pitch_shift)
317
 
318
 
319
  # ---------------------------------------------------------------------------
320
- # Gradio callbacks
321
  # ---------------------------------------------------------------------------
322
 
323
- def cb_rain(rain_type, drop_size, drops_sec, intensity, brightness, resonance, stereo):
324
- audio = synthesize_rain(rain_type, drop_size, drops_sec, intensity, brightness, resonance, stereo)
325
  return (SR, audio.astype(np.float32))
326
 
327
 
@@ -332,173 +413,98 @@ def cb_tonal(grain_size, density, randomness, pitch_shift, freq):
332
 
333
 
334
  # ---------------------------------------------------------------------------
335
- # Custom CSS — dark theme inspired by Material for MkDocs
336
  # ---------------------------------------------------------------------------
337
 
338
- CUSTOM_CSS = """
339
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400&display=swap');
340
-
341
- /* ── Global overrides ── */
342
- .gradio-container {
343
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
344
- background: #0d1117 !important;
345
- color: #c9d1d9 !important;
346
- max-width: 1100px !important;
347
- margin: auto !important;
348
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
- /* ── Remove default Gradio footer ── */
351
  footer { display: none !important; }
352
-
353
- /* ── Typography ── */
354
- h1, h2, h3 {
355
- font-family: 'Inter', sans-serif !important;
356
- font-weight: 600 !important;
357
- color: #e6edf3 !important;
358
- letter-spacing: -0.02em !important;
359
- }
360
- h1 { font-size: 1.75rem !important; }
361
- h3 { font-size: 1.05rem !important; color: #8b949e !important; }
362
-
363
- p, span, label, .gr-prose {
364
- font-family: 'Inter', sans-serif !important;
365
- color: #c9d1d9 !important;
366
- font-size: 0.9rem !important;
367
- line-height: 1.6 !important;
368
- }
369
-
370
- /* ── Panels and cards ── */
371
- .gr-panel, .gr-box, .gr-form, .gr-block {
372
- background: #161b22 !important;
373
- border: 1px solid #21262d !important;
374
- border-radius: 8px !important;
375
- }
376
-
377
- /* ── Tabs ── */
378
  .tab-nav button {
379
- font-family: 'Inter', sans-serif !important;
380
  font-weight: 500 !important;
381
- font-size: 0.9rem !important;
382
- color: #8b949e !important;
383
  border: none !important;
384
- background: transparent !important;
385
- padding: 10px 20px !important;
386
  border-bottom: 2px solid transparent !important;
387
  }
388
  .tab-nav button.selected {
389
  color: #58a6ff !important;
390
- border-bottom: 2px solid #58a6ff !important;
391
- }
392
-
393
- /* ── Sliders ── */
394
- input[type="range"] {
395
- accent-color: #58a6ff !important;
396
- }
397
- .gr-slider label {
398
- font-weight: 500 !important;
399
- }
400
-
401
- /* ── Buttons ── */
402
- .gr-button-primary {
403
- background: #238636 !important;
404
- border: 1px solid #2ea043 !important;
405
- color: #ffffff !important;
406
- font-family: 'Inter', sans-serif !important;
407
- font-weight: 500 !important;
408
- border-radius: 6px !important;
409
- padding: 8px 24px !important;
410
- transition: background 0.15s ease !important;
411
- }
412
- .gr-button-primary:hover {
413
- background: #2ea043 !important;
414
- }
415
-
416
- /* ── Radio buttons ── */
417
- .gr-radio label {
418
- font-family: 'Inter', sans-serif !important;
419
- }
420
-
421
- /* ── Audio player ── */
422
- audio {
423
- border-radius: 6px !important;
424
- }
425
-
426
- /* ── Tables in markdown ── */
427
- table {
428
- font-family: 'Inter', sans-serif !important;
429
- font-size: 0.82rem !important;
430
- border-collapse: collapse !important;
431
- width: 100% !important;
432
- }
433
- th {
434
- background: #21262d !important;
435
- color: #8b949e !important;
436
- font-weight: 500 !important;
437
- padding: 8px 12px !important;
438
- text-align: left !important;
439
- }
440
- td {
441
- padding: 6px 12px !important;
442
- border-top: 1px solid #21262d !important;
443
- color: #c9d1d9 !important;
444
- }
445
-
446
- /* ── Info text under sliders ── */
447
- .gr-info {
448
- font-size: 0.78rem !important;
449
- color: #6e7681 !important;
450
- font-style: normal !important;
451
- }
452
-
453
- /* ── Code / mono ── */
454
- code, .mono {
455
- font-family: 'JetBrains Mono', monospace !important;
456
- font-size: 0.82rem !important;
457
- background: #21262d !important;
458
- padding: 2px 6px !important;
459
- border-radius: 4px !important;
460
- }
461
-
462
- /* ── Accent color for links ── */
463
- a { color: #58a6ff !important; }
464
-
465
- /* ── Divider ── */
466
- hr {
467
- border: none !important;
468
- border-top: 1px solid #21262d !important;
469
- margin: 1.5rem 0 !important;
470
  }
 
 
 
471
  """
472
 
473
-
474
  # ---------------------------------------------------------------------------
475
  # UI
476
  # ---------------------------------------------------------------------------
477
 
478
- with gr.Blocks(
479
- title="Granular Synthesis · Rain",
480
- css=CUSTOM_CSS,
481
- theme=gr.themes.Base(),
482
- ) as demo:
483
 
484
  gr.Markdown(
485
  """
486
- # Granular Synthesis — Interactive Demo
487
- ### Micro-sound, grain clouds, texture design
488
  """
489
  )
490
 
491
  with gr.Tabs():
492
 
493
- # ======================== RAIN TAB ========================
494
  with gr.TabItem("Rain Simulation"):
495
  gr.Markdown(
496
  """
497
- Each raindrop is a **noise micro-burst** shaped by an exponential envelope
498
- and a resonant low-pass filter. Thousands of them, scattered randomly in time
499
- with per-drop variation in size, brightness, and stereo position, create rain.
500
- This is granular synthesis but instead of slicing an existing recording,
501
- each grain is **procedurally generated**.
502
  """
503
  )
504
 
@@ -508,37 +514,37 @@ with gr.Blocks(
508
  choices=["light", "medium", "heavy", "thunder"],
509
  value="medium",
510
  label="Rain type",
511
- info="Affects density multiplier, spectral content, and optional layers.",
512
- )
513
- drop_size = gr.Slider(
514
- minimum=2, maximum=60, value=18, step=1,
515
- label="Drop size (ms)",
516
- info="Grain duration. Larger → splashier, more resonant.",
517
- )
518
- rain_density = gr.Slider(
519
- minimum=10, maximum=400, value=100, step=5,
520
- label="Drops / second",
521
- info="Base rate before type multiplier.",
522
- )
523
- rain_intensity = gr.Slider(
524
- minimum=0.5, maximum=5.0, value=1.5, step=0.1,
525
- label="Intensity",
526
- info="Global density and wash volume scaling.",
527
  )
528
  brightness = gr.Slider(
529
- minimum=0.0, maximum=1.0, value=0.45, step=0.01,
530
  label="Surface brightness",
531
- info="Low-pass cutoff. 0 earth / foliage (dark). 1 glass / tin (bright).",
 
 
 
 
 
532
  )
533
- resonance = gr.Slider(
534
- minimum=0.0, maximum=1.0, value=0.3, step=0.01,
535
- label="Surface resonance",
536
- info="Filter Q. Higher surface rings more (metallic).",
537
  )
538
  stereo = gr.Slider(
539
- minimum=0.0, maximum=1.0, value=0.7, step=0.01,
540
  label="Stereo width",
541
- info="0 mono centre. 1 full L/R scatter.",
 
 
 
 
 
 
 
 
 
 
542
  )
543
  rain_btn = gr.Button("Generate rain", variant="primary", size="lg")
544
 
@@ -547,26 +553,26 @@ with gr.Blocks(
547
 
548
  gr.Markdown(
549
  """
550
- **Presets to try**
551
 
552
- | Scene | Type | ms | d/s | Int | Bright | Res |
553
  |---|---|---|---|---|---|---|
554
- | Drizzle on leaves | light | 10 | 30 | 1.0 | 0.2 | 0.1 |
555
- | Window at night | medium | 18 | 100 | 1.5 | 0.5 | 0.3 |
556
- | Tin roof | medium | 12 | 140 | 2.0 | 0.9 | 0.8 |
557
- | Downpour | heavy | 25 | 250 | 3.0 | 0.4 | 0.2 |
558
- | Thunderstorm | thunder | 30 | 300 | 4.0 | 0.35 | 0.25 |
559
- | Forest canopy | light | 22 | 50 | 1.0 | 0.15 | 0.5 |
560
  """
561
  )
562
 
563
  rain_btn.click(
564
  fn=cb_rain,
565
- inputs=[rain_type, drop_size, rain_density, rain_intensity, brightness, resonance, stereo],
566
  outputs=rain_audio,
567
  )
568
 
569
- # ======================== TONAL TAB ========================
570
  with gr.TabItem("Tonal Granular"):
571
  gr.Markdown(
572
  """
@@ -578,10 +584,10 @@ with gr.Blocks(
578
  with gr.Column(scale=1):
579
  source_freq = gr.Slider(80, 880, 220, step=1, label="Source frequency (Hz)")
580
  grain_size = gr.Slider(5, 200, 50, step=1, label="Grain size (ms)",
581
- info="Smaller buzzy. Larger smooth.")
582
  tonal_density = gr.Slider(1, 8, 4, step=0.5, label="Density (overlap)")
583
  randomness_sl = gr.Slider(0, 1, 0.3, step=0.01, label="Position randomness",
584
- info="0 sequential. 1 fully random (freeze/texture).")
585
  pitch = gr.Slider(0.25, 4.0, 1.0, step=0.05, label="Pitch shift")
586
  tonal_btn = gr.Button("Synthesize", variant="primary", size="lg")
587
 
@@ -591,8 +597,8 @@ with gr.Blocks(
591
  """
592
  **Signal chain**
593
 
594
- Source (additive harmonics) grain extraction (sequential + random blend)
595
- Hann window (click-free edges) overlap-add normalize
596
  """
597
  )
598
 
@@ -605,7 +611,7 @@ with gr.Blocks(
605
  gr.Markdown(
606
  """
607
  ---
608
- Built with Python and Gradio no audio samples, everything is synthesized from scratch.
609
  Part of [Generative Audio Soundscapes Lab](https://my-sonicase.github.io/genaudio-soundscapes/).
610
  """
611
  )
 
1
  """
2
+ Granular Synthesis Demo // Rain Simulation (v3)
3
+ ================================================
4
+
5
+ Why v1/v2 sounded like frying bacon:
6
+ The old approach generated individual noise-burst "drops" and summed them.
7
+ This creates a sparse, clicky texture because:
8
+ 1. Short noise bursts have flat spectra (white noise = frying sound)
9
+ 2. Box/naive filters barely shape the spectrum
10
+ 3. Individual grains are too sparse to fuse into a continuous texture
11
+
12
+ Real rain is NOT a sum of isolated clicks. Acoustically, rain is a
13
+ CONTINUOUS stochastic process with a specific spectral shape:
14
+ - Energy concentrated between 1 kHz and 15 kHz
15
+ - Peak around 5-8 kHz (research: Nystuen et al., raindrop acoustics)
16
+ - Spectral slope that varies with rain intensity
17
+ - Slow amplitude modulation (gusts, intensity fluctuation)
18
+ - Small drops produce 13-25 kHz (drizzle shimmer)
19
+ - Large drops add energy below 2 kHz (heavy rain rumble)
20
+
21
+ v3 approach: spectral domain synthesis.
22
+ 1. Generate white noise in the frequency domain (FFT)
23
+ 2. Sculpt the spectrum to match real rain profiles
24
+ 3. Add temporal modulation (amplitude envelopes that breathe)
25
+ 4. Layer: continuous wash + transient drops + optional thunder
26
+ 5. Stereo decorrelation for spatial width
27
+
28
+ This is still granular thinking: the "grains" are now overlapping
29
+ FFT frames (STFT), each with a shaped spectrum. The overlap-add
30
+ reconstruction is the same principle as classic granular synthesis.
31
  """
32
 
33
  import numpy as np
34
+ from scipy import signal as sig
35
+ from scipy.fft import rfft, irfft
36
  import gradio as gr
37
 
38
  # ---------------------------------------------------------------------------
39
  # Constants
40
  # ---------------------------------------------------------------------------
41
  SR = 44100
42
+ DURATION = 7.0 # seconds
43
 
44
  # ---------------------------------------------------------------------------
45
+ # Spectral rain profile
46
  # ---------------------------------------------------------------------------
47
 
48
+ def rain_spectral_profile(
49
+ n_fft: int,
50
+ brightness: float,
51
+ rain_type: str,
52
+ ) -> np.ndarray:
53
  """
54
+ Build a frequency-domain magnitude envelope that matches
55
+ the spectral shape of real rainfall.
56
 
57
+ Based on underwater acoustic rainfall studies:
58
+ small drops peak at 13-25 kHz, large drops are broadband 1-50 kHz,
59
+ most rain energy sits in the 2-12 kHz band.
 
 
60
 
61
+ We model this as a bandpass profile (skewed Gaussian in log-frequency)
62
+ whose center frequency and bandwidth shift with brightness and rain type.
63
  """
64
+ n_bins = n_fft // 2 + 1
65
+ freqs = np.linspace(0, SR / 2, n_bins)
66
+
67
+ # Avoid log(0)
68
+ freqs_safe = np.maximum(freqs, 1.0)
69
+ log_freqs = np.log2(freqs_safe)
70
+
71
+ # Center frequency shifts with brightness
72
+ # Low brightness (dark/soil): center around 2 kHz
73
+ # High brightness (glass/metal): center around 8 kHz
74
+ center_hz = 1500 * (2.0 ** (brightness * 2.5)) # 1.5 kHz to ~8.5 kHz
75
+ center_log = np.log2(center_hz)
76
+
77
+ # Bandwidth in octaves (wider for heavy rain)
78
+ bw_map = {"light": 1.8, "medium": 2.2, "heavy": 3.0, "thunder": 3.5}
79
+ bw = bw_map.get(rain_type, 2.2)
80
+
81
+ # Skewed Gaussian in log-frequency space
82
+ profile = np.exp(-0.5 * ((log_freqs - center_log) / bw) ** 2)
83
+
84
+ # Add high-frequency shimmer for light rain (drizzle peak at 13-25 kHz)
85
+ if rain_type == "light":
86
+ shimmer_center = np.log2(16000)
87
+ shimmer = 0.4 * np.exp(-0.5 * ((log_freqs - shimmer_center) / 0.5) ** 2)
88
+ profile += shimmer
89
+
90
+ # Add sub-bass rumble for heavy/thunder
91
+ if rain_type in ("heavy", "thunder"):
92
+ bass_center = np.log2(300)
93
+ bass = 0.3 * np.exp(-0.5 * ((log_freqs - bass_center) / 1.0) ** 2)
94
+ profile += bass
95
+
96
+ # Roll off everything below 80 Hz (rumble is not rain)
97
+ highpass = 1.0 / (1.0 + (80.0 / freqs_safe) ** 4)
98
+ profile *= highpass
99
 
100
  # Normalize
101
+ profile /= np.max(profile) + 1e-12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
+ return profile
 
 
 
 
 
 
 
 
 
 
 
104
 
105
 
106
  # ---------------------------------------------------------------------------
107
+ # Temporal modulation (rain is not perfectly steady)
108
  # ---------------------------------------------------------------------------
109
 
110
+ def make_modulation(n_samples: int, speed: float = 0.2) -> np.ndarray:
 
 
 
 
111
  """
112
+ Slow amplitude modulation to simulate natural intensity fluctuation.
113
+ Rain intensity varies over seconds (gusts, cloud cells passing).
 
 
 
 
114
 
115
+ We sum a few slow random sinusoids to create an organic envelope.
 
 
 
116
  """
117
+ t = np.linspace(0, DURATION, n_samples)
118
+ mod = np.ones(n_samples, dtype=np.float64)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
+ # Sum of 4 slow sinusoids with random phases
121
+ for i in range(4):
122
+ freq = speed * (0.5 + i * 0.3) + np.random.uniform(-0.05, 0.05)
123
+ phase = np.random.uniform(0, 2 * np.pi)
124
+ depth = 0.08 + 0.07 * i # increasing modulation depth
125
+ mod += depth * np.sin(2 * np.pi * freq * t + phase)
126
+
127
+ # Keep in a reasonable range
128
+ mod = np.clip(mod, 0.3, 1.5)
129
+ # Smooth with a gentle low-pass to avoid sudden jumps
130
+ window = np.hanning(int(SR * 0.3))
131
+ window /= window.sum()
132
+ mod = np.convolve(mod, window, mode="same")
133
+
134
+ return mod
135
 
136
 
137
  # ---------------------------------------------------------------------------
138
+ # Core: spectral rain synthesis via overlap-add STFT
139
  # ---------------------------------------------------------------------------
140
 
141
  def synthesize_rain(
142
  rain_type: str,
143
+ brightness: float,
144
+ density: float,
145
+ modulation_speed: float,
 
 
146
  stereo_width: float,
147
+ highcut: float,
148
+ lowcut: float,
149
  ) -> np.ndarray:
150
  """
151
+ Synthesize rain using FFT-based spectral shaping.
 
 
 
 
 
152
 
153
+ This is granular synthesis at the frame level:
154
+ each STFT frame is a "grain" whose spectrum is sculpted,
155
+ and the overlap-add reconstruction creates the continuous texture.
156
  """
157
  n_out = int(DURATION * SR)
158
+
159
+ # FFT parameters
160
+ # 2048 samples at 44.1kHz = ~46ms frames. This is our "grain size"
161
+ # in the spectral domain. Overlap of 75% ensures smooth transitions.
162
+ n_fft = 2048
163
+ hop = n_fft // 4 # 75% overlap (standard for STFT)
164
+ n_frames = (n_out // hop) + 1
165
+ n_bins = n_fft // 2 + 1
166
+
167
+ # Build the target spectral profile
168
+ profile = rain_spectral_profile(n_fft, brightness, rain_type)
169
+
170
+ # Apply density scaling (affects overall energy)
171
+ profile *= (0.3 + density * 0.7)
172
+
173
+ # Apply frequency range limits from sliders
174
+ freqs = np.linspace(0, SR / 2, n_bins)
175
+ # Gentle roll-off at the edges (not a brick wall, which sounds unnatural)
176
+ low_rolloff = 1.0 / (1.0 + (lowcut / (freqs + 1e-6)) ** 6)
177
+ high_rolloff = 1.0 / (1.0 + (freqs / highcut) ** 6)
178
+ profile *= low_rolloff * high_rolloff
179
+
180
+ # Synthesis window (Hann for overlap-add, same as classic granular)
181
+ window = np.hanning(n_fft)
182
+
183
+ # Two independent channels for stereo
184
+ output_L = np.zeros(n_out + n_fft, dtype=np.float64)
185
+ output_R = np.zeros(n_out + n_fft, dtype=np.float64)
186
+
187
+ for frame in range(n_frames):
188
+ # Generate random phase noise in the frequency domain.
189
+ # This is the key insight: white noise = uniform random phase
190
+ # + flat magnitude. By keeping random phase but imposing our
191
+ # spectral profile as magnitude, we get colored noise that
192
+ # matches the rain spectrum exactly.
193
+
194
+ # Left channel
195
+ phase_L = np.random.uniform(0, 2 * np.pi, n_bins)
196
+ spectrum_L = profile * np.exp(1j * phase_L)
197
+ grain_L = irfft(spectrum_L, n=n_fft).real * window
198
+
199
+ # Right channel: independent phase for stereo decorrelation.
200
+ # stereo_width controls how different L and R are.
201
+ # width=0: identical (mono). width=1: fully independent.
202
+ if stereo_width > 0.01:
203
+ phase_R = phase_L * (1 - stereo_width) + np.random.uniform(0, 2 * np.pi, n_bins) * stereo_width
204
+ spectrum_R = profile * np.exp(1j * phase_R)
205
+ grain_R = irfft(spectrum_R, n=n_fft).real * window
206
+ else:
207
+ grain_R = grain_L.copy()
208
+
209
+ # Place grain in output (overlap-add)
210
+ pos = frame * hop
211
+ if pos + n_fft <= len(output_L):
212
+ output_L[pos:pos + n_fft] += grain_L
213
+ output_R[pos:pos + n_fft] += grain_R
214
+
215
+ # Trim to exact length
216
+ output_L = output_L[:n_out]
217
+ output_R = output_R[:n_out]
218
+
219
+ # Apply temporal modulation
220
+ mod = make_modulation(n_out, speed=modulation_speed)
221
+ output_L *= mod
222
+ output_R *= mod
223
+
224
+ # Add transient drop layer for texture (sparse individual drops on top)
225
+ drop_layer_L, drop_layer_R = make_drop_layer(n_out, rain_type, brightness, density)
226
+ # Drops are much quieter than the continuous layer
227
+ drop_mix = {"light": 0.5, "medium": 0.3, "heavy": 0.15, "thunder": 0.1}
228
+ dmix = drop_mix.get(rain_type, 0.3)
229
+ output_L += drop_layer_L * dmix
230
+ output_R += drop_layer_R * dmix
231
+
232
+ # Thunder
233
+ if rain_type == "thunder":
234
+ th_L, th_R = make_thunder(n_out)
235
+ output_L += th_L
236
+ output_R += th_R
237
+
238
+ # Final normalization
239
+ stereo = np.column_stack([output_L, output_R])
240
+ peak = np.max(np.abs(stereo))
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  if peak > 0:
242
+ stereo *= 0.85 / peak
243
 
244
+ return stereo
245
+
246
+
247
+ # ---------------------------------------------------------------------------
248
+ # Transient drop layer (sparse individual drops for texture)
249
+ # ---------------------------------------------------------------------------
250
+
251
+ def make_drop_layer(
252
+ n_out: int,
253
+ rain_type: str,
254
+ brightness: float,
255
+ density: float,
256
+ ) -> tuple:
257
+ """
258
+ Sparse individual drops layered on top of the continuous wash.
259
+ These provide the "pointillistic" detail that makes rain sound alive.
260
+ Without them, the wash alone sounds like generic colored noise.
261
+ """
262
+ output_L = np.zeros(n_out, dtype=np.float64)
263
+ output_R = np.zeros(n_out, dtype=np.float64)
264
+
265
+ # Number of audible drops (not all rain drops are individually heard)
266
+ drops_per_sec = {"light": 8, "medium": 20, "heavy": 40, "thunder": 50}
267
+ n_drops = int(drops_per_sec.get(rain_type, 20) * density * DURATION)
268
+
269
+ # Drop duration in samples (10-40ms)
270
+ base_dur = int(SR * 0.02)
271
+
272
+ # Cutoff frequency for drops (matches surface brightness)
273
+ cutoff_base = 1000 * (2.0 ** (brightness * 3.0)) # 1kHz to 8kHz
274
+
275
+ for _ in range(n_drops):
276
+ pos = np.random.randint(0, max(n_out - base_dur * 3, 1))
277
+
278
+ # Each drop varies in duration and brightness
279
+ dur = int(base_dur * np.random.uniform(0.5, 2.0))
280
+ dur = max(dur, 64)
281
+
282
+ # Synthesize drop: filtered noise with sharp exponential decay
283
+ t = np.linspace(0, 1, dur)
284
+ envelope = np.exp(-np.random.uniform(8, 20) * t)
285
+ noise = np.random.randn(dur) * envelope
286
+
287
+ # Bandpass filter each drop using scipy
288
+ # Cutoff varies per drop for realism
289
+ this_cutoff = cutoff_base * np.random.uniform(0.5, 1.5)
290
+ this_cutoff = min(this_cutoff, SR * 0.45)
291
+ low = max(this_cutoff * 0.3, 100)
292
+
293
+ try:
294
+ sos = sig.butter(2, [low, this_cutoff], btype="bandpass", fs=SR, output="sos")
295
+ drop = sig.sosfilt(sos, noise)
296
+ except Exception:
297
+ drop = noise # fallback if filter params are out of range
298
+
299
+ # Random amplitude (distance simulation)
300
+ amp = np.random.uniform(0.1, 1.0) ** 1.3
301
+
302
+ # Stereo position
303
+ pan = np.random.uniform(0, 1)
304
+ L_gain = np.cos(pan * np.pi / 2) * amp
305
+ R_gain = np.sin(pan * np.pi / 2) * amp
306
+
307
+ end = min(pos + dur, n_out)
308
+ seg = drop[:end - pos]
309
+ output_L[pos:end] += seg * L_gain
310
+ output_R[pos:end] += seg * R_gain
311
+
312
+ return output_L, output_R
313
+
314
+
315
+ # ---------------------------------------------------------------------------
316
+ # Thunder
317
+ # ---------------------------------------------------------------------------
318
+
319
+ def make_thunder(n_out: int) -> tuple:
320
+ """Low-frequency rumble events with slow attack and long tail."""
321
+ L = np.zeros(n_out, dtype=np.float64)
322
+ R = np.zeros(n_out, dtype=np.float64)
323
+
324
+ n_events = np.random.randint(1, 3)
325
+ for _ in range(n_events):
326
+ pos = np.random.randint(0, n_out // 2)
327
+ dur = int(SR * np.random.uniform(2.0, 4.0))
328
+ t = np.linspace(0, 1, dur)
329
+
330
+ # Sum of low frequencies with random phases
331
+ rumble = np.zeros(dur)
332
+ for f in [20, 30, 45, 60, 80, 100]:
333
+ phase = np.random.uniform(0, 2 * np.pi)
334
+ rumble += np.sin(2 * np.pi * f * t + phase) * np.random.uniform(0.3, 1.0)
335
+
336
+ # Envelope: slow build, long decay
337
+ env = np.exp(-1.0 * t) * (1 - np.exp(-6 * t))
338
+ rumble *= env * 0.4
339
+
340
+ end = min(pos + dur, n_out)
341
+ seg = rumble[:end - pos]
342
+
343
+ # Slightly different L/R for width
344
+ L[pos:end] += seg * np.random.uniform(0.7, 1.0)
345
+ R[pos:end] += seg * np.random.uniform(0.7, 1.0)
346
+
347
+ return L, R
348
 
349
 
350
  # ---------------------------------------------------------------------------
351
+ # Tonal granular engine (unchanged)
352
  # ---------------------------------------------------------------------------
353
 
354
  def make_tonal_source(freq: float = 220.0, duration: float = 2.0) -> np.ndarray:
355
  t = np.linspace(0, duration, int(SR * duration), endpoint=False)
356
+ s = np.zeros_like(t)
357
  for k in range(1, 8):
358
+ s += (1.0 / k) * np.sin(2 * np.pi * freq * k * t)
359
+ s /= np.max(np.abs(s))
360
+ return s
361
 
362
 
363
  def granular_synthesize(source, grain_size_ms, density, randomness, pitch_shift):
364
  grain_samples = max(int((grain_size_ms / 1000.0) * SR), 64)
365
  window = np.hanning(grain_samples)
366
  hop = max(int(grain_samples / density), 1)
 
367
  n_out = int(DURATION * SR)
368
  output = np.zeros(n_out, dtype=np.float64)
369
 
 
384
  rand_pos = np.random.randint(0, max(src_len - grain_samples, 1))
385
  start = int(seq_pos * (1 - randomness) + rand_pos * randomness)
386
  start = np.clip(start, 0, src_len - grain_samples)
 
387
  grain = pitched[start: start + grain_samples] * window
388
  out_pos = i * hop
389
  if out_pos + grain_samples > n_out:
 
398
 
399
 
400
  # ---------------------------------------------------------------------------
401
+ # Callbacks
402
  # ---------------------------------------------------------------------------
403
 
404
+ def cb_rain(rain_type, brightness, density, mod_speed, stereo, highcut, lowcut):
405
+ audio = synthesize_rain(rain_type, brightness, density, mod_speed, stereo, highcut, lowcut)
406
  return (SR, audio.astype(np.float32))
407
 
408
 
 
413
 
414
 
415
  # ---------------------------------------------------------------------------
416
+ # Theme + CSS
417
  # ---------------------------------------------------------------------------
418
 
419
+ dark_theme = gr.themes.Base(
420
+ primary_hue=gr.themes.colors.blue,
421
+ secondary_hue=gr.themes.colors.slate,
422
+ neutral_hue=gr.themes.colors.slate,
423
+ font=gr.themes.GoogleFont("Inter"),
424
+ font_mono=gr.themes.GoogleFont("JetBrains Mono"),
425
+ ).set(
426
+ body_background_fill="#0d1117",
427
+ body_background_fill_dark="#0d1117",
428
+ body_text_color="#c9d1d9",
429
+ body_text_color_dark="#c9d1d9",
430
+ body_text_color_subdued="#8b949e",
431
+ body_text_color_subdued_dark="#8b949e",
432
+ background_fill_primary="#161b22",
433
+ background_fill_primary_dark="#161b22",
434
+ background_fill_secondary="#0d1117",
435
+ background_fill_secondary_dark="#0d1117",
436
+ block_background_fill="#161b22",
437
+ block_background_fill_dark="#161b22",
438
+ block_border_color="#21262d",
439
+ block_border_color_dark="#21262d",
440
+ block_label_text_color="#8b949e",
441
+ block_label_text_color_dark="#8b949e",
442
+ block_title_text_color="#e6edf3",
443
+ block_title_text_color_dark="#e6edf3",
444
+ border_color_primary="#21262d",
445
+ border_color_primary_dark="#21262d",
446
+ button_primary_background_fill="#238636",
447
+ button_primary_background_fill_dark="#238636",
448
+ button_primary_background_fill_hover="#2ea043",
449
+ button_primary_background_fill_hover_dark="#2ea043",
450
+ button_primary_text_color="#ffffff",
451
+ button_primary_text_color_dark="#ffffff",
452
+ button_secondary_background_fill="#21262d",
453
+ button_secondary_background_fill_dark="#21262d",
454
+ button_secondary_text_color="#c9d1d9",
455
+ button_secondary_text_color_dark="#c9d1d9",
456
+ input_background_fill="#0d1117",
457
+ input_background_fill_dark="#0d1117",
458
+ input_border_color="#30363d",
459
+ input_border_color_dark="#30363d",
460
+ slider_color="#58a6ff",
461
+ slider_color_dark="#58a6ff",
462
+ link_text_color="#58a6ff",
463
+ link_text_color_dark="#58a6ff",
464
+ )
465
 
466
+ CUSTOM_CSS = """
467
  footer { display: none !important; }
468
+ h1 { letter-spacing: -0.03em !important; font-weight: 600 !important; }
469
+ h3 { color: #8b949e !important; font-weight: 400 !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  .tab-nav button {
 
471
  font-weight: 500 !important;
 
 
472
  border: none !important;
 
 
473
  border-bottom: 2px solid transparent !important;
474
  }
475
  .tab-nav button.selected {
476
  color: #58a6ff !important;
477
+ border-bottom-color: #58a6ff !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  }
479
+ table { font-size: 0.82rem !important; }
480
+ th { background: #21262d !important; color: #8b949e !important; font-weight: 500 !important; }
481
+ td { border-top: 1px solid #21262d !important; }
482
  """
483
 
 
484
  # ---------------------------------------------------------------------------
485
  # UI
486
  # ---------------------------------------------------------------------------
487
 
488
+ with gr.Blocks(title="Granular Synthesis", css=CUSTOM_CSS, theme=dark_theme) as demo:
 
 
 
 
489
 
490
  gr.Markdown(
491
  """
492
+ # Granular Synthesis
493
+ ### micro-sound, grain clouds, texture design
494
  """
495
  )
496
 
497
  with gr.Tabs():
498
 
499
+ # ======================== RAIN ========================
500
  with gr.TabItem("Rain Simulation"):
501
  gr.Markdown(
502
  """
503
+ Spectral-domain rain synthesis. Instead of summing noise clicks,
504
+ we sculpt white noise in the frequency domain to match the spectral
505
+ profile of real rainfall (energy concentrated 2 to 12 kHz, slope varies
506
+ with intensity). Each STFT frame is a "grain" whose spectrum is shaped
507
+ by the rain profile, then overlap-added into the output.
508
  """
509
  )
510
 
 
514
  choices=["light", "medium", "heavy", "thunder"],
515
  value="medium",
516
  label="Rain type",
517
+ info="Controls spectral shape, transient density, and optional layers.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  )
519
  brightness = gr.Slider(
520
+ 0.0, 1.0, 0.45, step=0.01,
521
  label="Surface brightness",
522
+ info="0 = dark (earth, foliage). 1 = bright (glass, tin roof).",
523
+ )
524
+ rain_density = gr.Slider(
525
+ 0.2, 3.0, 1.0, step=0.1,
526
+ label="Density",
527
+ info="Overall thickness of the rain texture.",
528
  )
529
+ mod_speed = gr.Slider(
530
+ 0.05, 1.0, 0.2, step=0.05,
531
+ label="Modulation speed",
532
+ info="How fast the rain intensity fluctuates (gusts).",
533
  )
534
  stereo = gr.Slider(
535
+ 0.0, 1.0, 0.7, step=0.01,
536
  label="Stereo width",
537
+ info="0 = mono. 1 = fully decorrelated L/R.",
538
+ )
539
+ lowcut = gr.Slider(
540
+ 50, 2000, 150, step=10,
541
+ label="Low cut (Hz)",
542
+ info="Remove frequencies below this point.",
543
+ )
544
+ highcut = gr.Slider(
545
+ 2000, 20000, 14000, step=100,
546
+ label="High cut (Hz)",
547
+ info="Remove frequencies above this point.",
548
  )
549
  rain_btn = gr.Button("Generate rain", variant="primary", size="lg")
550
 
 
553
 
554
  gr.Markdown(
555
  """
556
+ **Presets**
557
 
558
+ | Scene | Type | Bright | Dens | Mod | LoCut | HiCut |
559
  |---|---|---|---|---|---|---|
560
+ | Drizzle on leaves | light | 0.2 | 0.6 | 0.1 | 200 | 18000 |
561
+ | Window at night | medium | 0.5 | 1.0 | 0.2 | 150 | 14000 |
562
+ | Tin roof | medium | 0.9 | 1.2 | 0.15 | 300 | 16000 |
563
+ | Downpour | heavy | 0.4 | 2.0 | 0.3 | 100 | 12000 |
564
+ | Thunderstorm | thunder | 0.35 | 2.5 | 0.4 | 80 | 10000 |
565
+ | Forest canopy | light | 0.15 | 0.5 | 0.08 | 200 | 15000 |
566
  """
567
  )
568
 
569
  rain_btn.click(
570
  fn=cb_rain,
571
+ inputs=[rain_type, brightness, rain_density, mod_speed, stereo, highcut, lowcut],
572
  outputs=rain_audio,
573
  )
574
 
575
+ # ======================== TONAL ========================
576
  with gr.TabItem("Tonal Granular"):
577
  gr.Markdown(
578
  """
 
584
  with gr.Column(scale=1):
585
  source_freq = gr.Slider(80, 880, 220, step=1, label="Source frequency (Hz)")
586
  grain_size = gr.Slider(5, 200, 50, step=1, label="Grain size (ms)",
587
+ info="Smaller = buzzy. Larger = smooth.")
588
  tonal_density = gr.Slider(1, 8, 4, step=0.5, label="Density (overlap)")
589
  randomness_sl = gr.Slider(0, 1, 0.3, step=0.01, label="Position randomness",
590
+ info="0 = sequential. 1 = fully random (freeze/texture).")
591
  pitch = gr.Slider(0.25, 4.0, 1.0, step=0.05, label="Pitch shift")
592
  tonal_btn = gr.Button("Synthesize", variant="primary", size="lg")
593
 
 
597
  """
598
  **Signal chain**
599
 
600
+ Source (additive harmonics) > grain extraction (sequential + random blend)
601
+ > Hann window (click-free edges) > overlap-add > normalize
602
  """
603
  )
604
 
 
611
  gr.Markdown(
612
  """
613
  ---
614
+ Built with Python, NumPy, SciPy and Gradio. Everything is synthesized from scratch, no samples.
615
  Part of [Generative Audio Soundscapes Lab](https://my-sonicase.github.io/genaudio-soundscapes/).
616
  """
617
  )
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
  numpy
 
2
  gradio
 
1
  numpy
2
+ scipy
3
  gradio