Repository Public License
1#!/usr/bin/env python32# ORIX Alarm3# File: Scripts/make-sounds.py4# Description: Synthesises every bundled sound (9 alarm loops, 5 soundscapes, 4 interface effects) into App/Resources/Sounds.5# All material is original: additive / FM synthesis, shaped noise, envelopes and a synthetic reverb.6# No sample from anywhere is used. Output is deterministic (fixed seeds).7#8# Regenerate: python3 Scripts/make-sounds.py (all files, then the check table)9# python3 Scripts/make-sounds.py rain ocean (only the named ids)10# python3 Scripts/make-sounds.py --check (decode the bundled files, print peak / RMS / seam)11# Requires: Python 3 + numpy, and macOS `afconvert` / `afinfo` for encoding.12# Formats: alarm sounds -> <id>.caf, IMA4, mono, 44.1 kHz, 8-20 s, seamless loop, peak about -1 dBFS13# (played by the system alert via AlarmKit `.named("<id>.caf")`, limit 30 s)14# soundscapes -> scape-<id>.m4a, AAC, stereo, 44.1 kHz, 72 s, seamless loop, peak about -4 dBFS15# interface fx -> fx-<name>.caf, 16-bit PCM, mono, 44.1 kHz, under 1 s16# The file names must match `SoundCatalog` in Packages/AlarmCore/Sources/AlarmCore/Models/Catalogs.swift.17#18# Author: Simon-Pierre Boucher19# Contact: contact@spboucher.ai20import math21import os22import subprocess23import sys24import tempfile25import wave2627import numpy as np2829SR = 4410030ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))31OUT = os.path.join(ROOT, "App", "Resources", "Sounds")32TAU = 2 * math.pi333435# ---------------------------------------------------------------- helpers3637def midi(note):38 """Frequency of a MIDI note number (69 = A4 = 440 Hz)."""39 return 440.0 * 2 ** ((note - 69) / 12)404142def frames(seconds):43 """Loop length in frames, multiple of 64 so IMA4 packets end exactly on the loop point."""44 return int(seconds * SR) // 64 * 64454647def tvec(dur):48 return np.arange(int(dur * SR)) / SR495051def fade(sig, attack=0.004, release=0.02):52 """Short raised-cosine fades to keep every event click-free."""53 n = len(sig)54 a, r = min(int(attack * SR), n // 2), min(int(release * SR), n // 2)55 out = sig.copy()56 if a > 0:57 out[:a] *= 0.5 - 0.5 * np.cos(np.pi * np.arange(a) / a)58 if r > 0:59 out[-r:] *= 0.5 + 0.5 * np.cos(np.pi * np.arange(r) / r)60 return out616263def place(buf, sig, t, gain=1.0, pan=0.0):64 """Adds `sig` at time `t`, wrapping around the end of the buffer: tails fold back into the head (seamless loop)."""65 if buf.ndim == 2 and buf.shape[0] == 1:66 buf = buf[0] # view: a one-channel 2-D buffer is written as mono67 n = buf.shape[-1]68 start = int(round(t * SR)) % n69 if buf.ndim == 2:70 angle = (pan + 1) * math.pi / 471 gains = (gain * math.cos(angle) * math.sqrt(2), gain * math.sin(angle) * math.sqrt(2))72 pos = 073 while pos < len(sig):74 k = min(len(sig) - pos, n - start)75 if buf.ndim == 2:76 buf[0, start:start + k] += gains[0] * sig[pos:pos + k]77 buf[1, start:start + k] += gains[1] * sig[pos:pos + k]78 else:79 buf[start:start + k] += gain * sig[pos:pos + k]80 pos += k81 start = 0828384def shaped_noise(n, rng, response):85 """White noise shaped in the frequency domain by `response(freqs)`. Periodic over n frames by construction."""86 spectrum = np.fft.rfft(rng.standard_normal(n))87 freqs = np.fft.rfftfreq(n, 1 / SR)88 out = np.fft.irfft(spectrum * response(freqs), n)89 return out / (np.max(np.abs(out)) + 1e-12)909192def band(lo, hi, slope=2.0):93 """Smooth band-pass magnitude response (Butterworth-like skirts)."""94 def response(f):95 f = np.maximum(f, 1e-3)96 return 1 / np.sqrt(1 + (lo / f) ** (2 * slope)) / np.sqrt(1 + (f / hi) ** (2 * slope))97 return response9899100def filt(sig, response):101 """Zero-phase circular filter (keeps loops seamless)."""102 n = sig.shape[-1]103 return np.fft.irfft(np.fft.rfft(sig, axis=-1) * response(np.fft.rfftfreq(n, 1 / SR)), n, axis=-1)104105106def reverb(sig, rng, seconds=1.8, wet=0.25, bright=5000.0, predelay=0.012):107 """Synthetic reverb: circular convolution with exponentially decaying shaped noise. The tail wraps (seamless loop)."""108 n = sig.shape[-1]109 m = min(n, int(seconds * 1.6 * SR))110 channels = sig.shape[0] if sig.ndim == 2 else 1111 out = []112 for c in range(channels):113 x = sig[c] if sig.ndim == 2 else sig114 t = np.arange(m) / SR115 ir = shaped_noise(m, rng, band(180, bright, 1.0)) * np.exp(-6.9 * t / seconds)116 ir[: int(0.002 * SR)] *= np.linspace(0, 1, int(0.002 * SR))117 ir = np.concatenate([np.zeros(int(predelay * SR)), ir])[:n]118 ir /= math.sqrt(np.sum(ir ** 2))119 tail = np.fft.irfft(np.fft.rfft(x) * np.fft.rfft(ir, n), n)120 out.append((1 - wet) * x + wet * tail)121 return np.stack(out) if sig.ndim == 2 else out[0]122123124def crossfade_loop(sig, loop_frames):125 """Seamless loop from a longer take: the part after the loop point is equal-power crossfaded into the head."""126 extra = sig.shape[-1] - loop_frames127 out = sig[..., :loop_frames].copy()128 x = np.arange(extra) / extra129 out[..., :extra] = sig[..., :extra] * np.sin(x * np.pi / 2) + sig[..., loop_frames:] * np.cos(x * np.pi / 2)130 return out131132133def finish(sig, peak_db, drive=0.0):134 """Removes DC, optionally soft-saturates (tanh) to raise loudness without clipping, then normalises the peak."""135 sig = sig - np.mean(sig, axis=-1, keepdims=True)136 sig = sig / (np.max(np.abs(sig)) + 1e-12)137 if drive > 0:138 sig = np.tanh(sig * (1 + drive)) / math.tanh(1 + drive)139 return sig / np.max(np.abs(sig)) * 10 ** (peak_db / 20)140141142# ---------------------------------------------------------------- instruments143144def piano(freq, dur, velocity=1.0, brightness=1.0):145 """Piano-like tone: slightly inharmonic partials, upper partials decay faster, soft hammer onset."""146 t = tvec(dur)147 out = np.zeros_like(t)148 for k in range(1, 10):149 f = k * freq * math.sqrt(1 + 0.00035 * k * k)150 if f > 9000:151 break152 amp = brightness ** (k - 1) / k ** 1.35153 decay = (1.1 + 0.55 * k) * (freq / 260) ** 0.35154 out += amp * np.exp(-decay * t) * np.sin(TAU * f * t + 0.3 * k)155 out *= 1 - np.exp(-t / 0.003)156 return fade(out, 0.002, 0.08) * velocity157158159def bell(freq, dur, velocity=1.0):160 """Bell / chime: inharmonic partial series with independent decays."""161 t = tvec(dur)162 ratios = [0.5, 1.0, 1.19, 1.56, 2.0, 2.51, 2.66, 3.01, 4.1]163 amps = [0.25, 1.0, 0.55, 0.35, 0.6, 0.25, 0.2, 0.18, 0.1]164 out = np.zeros_like(t)165 for r, a in zip(ratios, amps):166 if freq * r < 10000:167 out += a * np.exp(-t * (1.2 + 1.5 * r) * 3 / dur) * np.sin(TAU * freq * r * t)168 return fade(out, 0.002, 0.1) * velocity169170171def fm(freq, dur, ratio=2.0, index=3.0, index_decay=12.0, amp_decay=6.0, velocity=1.0):172 """Two-operator FM voice with a decaying modulation index (pluck / stab)."""173 t = tvec(dur)174 mod = index * np.exp(-index_decay * t) * np.sin(TAU * freq * ratio * t)175 return fade(np.exp(-amp_decay * t) * np.sin(TAU * freq * t + mod), 0.003, 0.03) * velocity176177178def sine(freq, dur, attack=0.02, release=0.3, harmonics=((1, 1.0),)):179 t = tvec(dur)180 out = sum(a * np.sin(TAU * freq * h * t) for h, a in harmonics)181 return fade(out, attack, release)182183184def pad(freq, dur, rng, attack, release, voices=5, detune=0.004, rolloff=1.6, top=7):185 """Warm pad: several slightly detuned voices of a soft additive spectrum, slow attack and release."""186 t = tvec(dur)187 out = np.zeros_like(t)188 for _ in range(voices):189 f = freq * (1 + detune * rng.uniform(-1, 1))190 for k in range(1, top + 1):191 if f * k < 8000:192 out += np.sin(TAU * f * k * t + rng.uniform(0, TAU)) / k ** rolloff193 return fade(out / voices, attack, release)194195196def chirp(rng, kind, base):197 """One synthesised bird call (frequency glide with amplitude shaping), never a recording."""198 def glide(f0, f1, dur, curve=1.0, vibrato=0.0, rate=30.0):199 t = tvec(dur)200 x = (t / dur) ** curve201 f = f0 + (f1 - f0) * x + vibrato * np.sin(TAU * rate * t)202 phase = TAU * np.cumsum(f) / SR203 env = np.sin(np.pi * np.clip(t / dur, 0, 1)) ** 1.5204 return env * (np.sin(phase) + 0.18 * np.sin(2 * phase))205 if kind == 0: # falling whistle206 return glide(base * 1.25, base * 0.85, rng.uniform(0.16, 0.26), 0.7)207 if kind == 1: # fast trill208 parts = []209 for i in range(int(rng.integers(4, 9))):210 parts.append(glide(base * 0.9, base * 1.2, 0.045, 1.0) * (0.6 + 0.4 * math.sin(i)))211 parts.append(np.zeros(int(0.022 * SR)))212 return np.concatenate(parts)213 if kind == 2: # two-note call214 return np.concatenate([glide(base, base * 1.02, 0.14), np.zeros(int(0.05 * SR)), glide(base * 0.79, base * 0.77, 0.22)])215 if kind == 3: # warble216 return glide(base * 0.95, base * 1.1, rng.uniform(0.3, 0.45), 1.0, vibrato=base * 0.07, rate=rng.uniform(18, 28))217 return np.concatenate([glide(base * 0.8, base * 1.3, 0.07, 2.0), np.zeros(int(0.03 * SR)), # rising triplet218 glide(base * 0.9, base * 1.4, 0.07, 2.0), np.zeros(int(0.03 * SR)), glide(base, base * 1.5, 0.1, 2.0)])219220221def birds(buf, rng, count, level=1.0, lo=2300.0, hi=5200.0):222 n = buf.shape[-1]223 for _ in range(count):224 t = rng.uniform(0, n / SR)225 base = rng.uniform(lo, hi)226 kind = int(rng.integers(0, 5))227 pan = rng.uniform(-0.8, 0.8)228 gain = level * rng.uniform(0.35, 1.0)229 for r in range(int(rng.integers(1, 4))): # a bird usually repeats its call230 place(buf, chirp(rng, kind, base * rng.uniform(0.98, 1.02)), t + r * rng.uniform(0.45, 0.8), gain * 0.85 ** r, pan)231232233def waves(n, rng, period, channels=1):234 """Ocean swell: low rumble plus hiss, each wave rising quickly and washing out slowly. Integer number of waves per loop."""235 count = max(1, round(n / SR / period))236 out = np.zeros((channels, n))237 env_low, env_hiss = np.zeros(n), np.zeros(n)238 for i in range(count):239 length = n / count / SR240 t = tvec(length * 1.5)241 x = t / (length * 1.5)242 shape = np.where(x < 0.3, np.sin(x / 0.3 * np.pi / 2) ** 2, np.exp(-(x - 0.3) * 5.0)) * np.sin(np.pi * np.clip(x * 1.02, 0, 1)) ** 0.25243 height = rng.uniform(0.6, 1.0)244 at = i * length + rng.uniform(-0.6, 0.6)245 place(env_low, fade(shape, 0.3, 0.5), at, height)246 place(env_hiss, fade(shape ** 1.8, 0.3, 0.5), at + length * 0.12, height)247 for c in range(channels):248 low = shaped_noise(n, rng, band(70, 650, 1.0))249 hiss = shaped_noise(n, rng, band(900, 6500, 1.0))250 out[c] = low * (0.22 + env_low) + 0.55 * hiss * (0.06 + env_hiss)251 return out if channels > 1 else out[0]252253254def rain(n, rng, channels=1, drops_per_second=28):255 """Rain: steady shaped noise plus thousands of tiny decaying pings (droplets)."""256 out = np.zeros((channels, n))257 for c in range(channels):258 out[c] = 0.5 * shaped_noise(n, rng, band(1200, 9000, 1.0)) + 0.35 * shaped_noise(n, rng, band(350, 1800, 1.0))259 for _ in range(int(n / SR * drops_per_second)):260 f = rng.uniform(1800, 6500)261 d = rng.uniform(0.006, 0.03)262 t = tvec(d * 5)263 drop = np.exp(-t / d) * np.sin(TAU * f * t * (1 + 0.3 * t / (d * 5)))264 place(out, fade(drop, 0.0005, 0.002), rng.uniform(0, n / SR), rng.uniform(0.15, 0.7), rng.uniform(-1, 1))265 return out if channels > 1 else out[0]266267268# ---------------------------------------------------------------- alarm sounds (mono loops)269270def classic_alarm(rng):271 n = frames(8.0)272 buf = np.zeros(n)273 harmonics = ((1, 1.0), (2, 0.28), (3, 0.42), (5, 0.12))274 for bar in range(8): # four beeps then a breath, alternating two tones275 for i in range(4):276 f = 988.0 if i % 2 == 0 else 1319.0277 place(buf, sine(f, 0.115, 0.004, 0.012, harmonics), bar * 1.0 + i * 0.16)278 return finish(reverb(buf, rng, 0.35, 0.08), -1.0, 0.6)279280281def gentle_piano(rng):282 beat = 60 / 76283 n = frames(16 * beat)284 buf = np.zeros(n)285 chords = [[60, 64, 67, 71, 74, 79, 76, 71], [57, 60, 64, 67, 72, 76, 72, 67]] # Cmaj9, Am9 arpeggios286 for bar, chord in enumerate(chords):287 for i, note in enumerate(chord):288 t = (bar * 8 + i) * beat + rng.uniform(-0.008, 0.008)289 place(buf, piano(midi(note + 12), 3.2, rng.uniform(0.75, 1.0), 0.92), t)290 place(buf, piano(midi(chord[0] - 12 + 12), 5.0, 0.55, 0.8), bar * 8 * beat)291 return finish(reverb(buf, rng, 2.4, 0.3, 6000), -1.0, 0.35)292293294def ambient_rise(rng):295 n = frames(20.0)296 buf = np.zeros(n)297 steps = [[62, 69, 74, 78], [64, 71, 76, 79], [66, 73, 78, 81], [69, 74, 78, 86]] # rising D major voicings298 for i, chord in enumerate(steps):299 for note in chord:300 place(buf, pad(midi(note), 6.5, rng, 2.6, 2.6, rolloff=1.3) * (0.55 + 0.15 * i), i * 5.0)301 place(buf, bell(midi(chord[-1] + 12), 4.0, 0.16 + 0.05 * i), i * 5.0 + 2.4)302 swell = 0.62 + 0.38 * np.sin(np.pi * ((np.arange(n) / n * 4) % 1.0)) ** 2303 return finish(reverb(buf * swell, rng, 3.0, 0.35, 7000), -1.0, 0.5)304305306def soft_electronic(rng):307 beat = 60 / 100308 n = frames(16 * beat)309 buf = np.zeros(n)310 sequence = [69, 72, 76, 79, 76, 72, 81, 76, 67, 72, 76, 79, 74, 72, 79, 76] # A minor pentatonic pulse311 for rep in range(2):312 for i, note in enumerate(sequence):313 t = (rep * 16 + i) * beat / 2314 accent = 1.0 if i % 4 == 0 else 0.72315 voice = fm(midi(note), 0.42, 1.0, 1.6, 9.0, 7.0, accent)316 place(buf, voice, t)317 place(buf, voice, t + beat * 0.75, 0.28) # dotted echo318 for i in range(16): # soft round pulse on every beat319 t = tvec(0.22)320 place(buf, fade(np.sin(TAU * (330 * np.exp(-t * 9) + 220) * t) * np.exp(-t * 14), 0.002, 0.03), i * beat, 0.55)321 return finish(reverb(buf, rng, 1.2, 0.2, 6500), -1.0, 0.5)322323324def energetic_wake(rng):325 beat = 60 / 140326 n = frames(32 * beat)327 buf = np.zeros(n)328 bars = [[72, 76, 79, 84], [74, 77, 81, 86], [76, 79, 84, 88], [79, 83, 86, 91]] # bright climbing major pattern329 for rep in range(2):330 for b, chord in enumerate(bars):331 for i in range(8):332 note = chord[[0, 1, 2, 3, 2, 3, 1, 2][i]]333 t = (rep * 16 + b * 4) * beat + i * beat / 2334 place(buf, fm(midi(note), 0.2, 2.0, 2.4, 16.0, 11.0, 1.0 if i % 2 == 0 else 0.78), t)335 place(buf, fm(midi(chord[0] - 12), 0.5, 1.0, 1.2, 8.0, 5.0, 0.6), (rep * 16 + b * 4) * beat)336 for i in range(64): # off-beat shaker337 hat = shaped_noise(int(0.05 * SR), rng, band(6000, 12000, 1.0)) * np.exp(-tvec(0.05)[: int(0.05 * SR)] * 70)338 place(buf, hat, i * beat / 2 + beat / 4, 0.16)339 return finish(reverb(buf, rng, 0.7, 0.14, 8000), -1.0, 0.7)340341342def minimal_tones(rng):343 n = frames(8.0)344 buf = np.zeros(n)345 for t, note, length in [(0.0, 76, 1.5), (1.0, 83, 1.5), (2.0, 80, 2.4), (4.0, 76, 1.5), (5.0, 85, 1.5), (6.0, 83, 2.2)]:346 place(buf, sine(midi(note), length, 0.03, length * 0.7, ((1, 1.0), (2, 0.08))), t)347 return finish(reverb(buf, rng, 1.6, 0.18, 6000), -1.0, 0.25)348349350def forest_birds(rng):351 n = frames(15.0)352 buf = np.zeros(n)353 birds(buf, rng, 16, 1.0, 2200, 4600)354 bed = shaped_noise(n, rng, band(500, 4500, 1.0))355 return finish(reverb(buf, rng, 1.4, 0.22, 7000) + 0.05 * bed, -1.0, 0.8)356357358def ocean_bell(rng):359 n = frames(18.0)360 sea = waves(n, rng, 6.0)361 buf = np.zeros(n)362 for i, note in enumerate([76, 81, 79, 83, 76, 86]): # buoy bell, unhurried363 place(buf, bell(midi(note), 3.4, 1.0), i * 3.0 + 0.8)364 return finish(0.45 * sea / np.max(np.abs(sea)) + 0.75 * reverb(buf, rng, 2.2, 0.28, 7000) / 1.6, -1.0, 0.6)365366367def rain_chime(rng):368 n = frames(16.0)369 wet = rain(n, rng)370 buf = np.zeros(n)371 scale = [79, 81, 84, 86, 88, 91, 93]372 for i in range(20):373 t = i * 0.8 + rng.uniform(-0.12, 0.12)374 place(buf, bell(midi(scale[int(rng.integers(0, len(scale)))]), 2.6, rng.uniform(0.6, 1.0)), t)375 chimes = reverb(buf, rng, 2.0, 0.3, 8000)376 return finish(0.28 * wet / np.max(np.abs(wet)) + 0.8 * chimes / np.max(np.abs(chimes)), -1.0, 0.6)377378379# ---------------------------------------------------------------- soundscapes (stereo, 72 s loops)380381SCAPE_SECONDS = 72.0382SCAPE_EXTRA = 6.0 # extra take crossfaded into the head for the noise-based scenes383384385def scape_ambient_sunrise(rng):386 n = frames(SCAPE_SECONDS)387 buf = np.zeros((2, n))388 chords = [[50, 57, 62, 66, 69], [47, 54, 62, 66, 71], [43, 55, 62, 67, 71], [45, 57, 64, 69, 73]] # D, Bm, G, A389 for i, chord in enumerate(chords):390 for j, note in enumerate(chord):391 place(buf, pad(midi(note), 24.0, rng, 7.0, 8.0, voices=4, rolloff=1.9), i * 18.0 - 3.0, 0.8 if j else 1.1, rng.uniform(-0.6, 0.6))392 for k in range(3): # slow shimmer notes393 place(buf, sine(midi(chord[-1] + 12 + [0, 7, 4][k]), 5.0, 1.6, 3.0), i * 18.0 + 4.0 + k * 4.5, 0.11, rng.uniform(-0.8, 0.8))394 air = np.stack([shaped_noise(n, rng, band(1500, 7000, 1.0)) for _ in range(2)])395 return finish(reverb(buf, rng, 4.5, 0.45, 5000) + 0.012 * air * np.max(np.abs(buf)), -4.0)396397398def scape_rain(rng):399 n, m = frames(SCAPE_SECONDS), frames(SCAPE_SECONDS) + int(SCAPE_EXTRA * SR)400 take = rain(m, rng, channels=2, drops_per_second=34)401 gust = 1 + 0.18 * np.sin(TAU * np.arange(m) / SR / 24.0) + 0.08 * np.sin(TAU * np.arange(m) / SR / 9.0 + 1.0)402 low = np.stack([shaped_noise(m, rng, band(60, 320, 1.0)) for _ in range(2)]) # distant roof rumble403 return finish(crossfade_loop(take * gust + 0.25 * low, n), -5.0)404405406def scape_forest(rng):407 n = frames(SCAPE_SECONDS)408 buf = np.zeros((2, n))409 birds(buf, rng, 46, 1.0, 2000, 5200)410 wind = np.stack([shaped_noise(n, rng, band(250, 2600, 1.0)) for _ in range(2)])411 breath = 0.6 + 0.4 * np.sin(TAU * np.arange(n) / n * 5 + 0.7) ** 2 # five slow gusts per loop (periodic)412 leaves = np.stack([shaped_noise(n, rng, band(3000, 9000, 1.0)) for _ in range(2)]) * breath413 scene = reverb(buf, rng, 1.8, 0.3, 7000)414 return finish(scene / np.max(np.abs(scene)) + 0.16 * wind * breath + 0.05 * leaves, -4.0)415416417def scape_ocean(rng):418 n = frames(SCAPE_SECONDS)419 sea = waves(n, rng, 9.0, channels=2)420 deep = shaped_noise(n, rng, band(40, 160, 1.0))421 return finish(sea + 0.2 * deep, -4.0)422423424def scape_piano_drift(rng):425 n = frames(SCAPE_SECONDS)426 buf = np.zeros((2, n))427 phrases = [[62, 69, 74, 78], [59, 66, 74, 76], [55, 67, 71, 74], [57, 64, 73, 76]] # same harmony family as the sunrise pad428 for i, chord in enumerate(phrases):429 base = i * 18.0430 place(buf, piano(midi(chord[0] - 12), 9.0, 0.7, 0.8), base, 1.0, -0.2)431 for k, at in enumerate([1.5, 4.0, 6.0, 9.5, 12.0, 14.5]):432 note = chord[[1, 2, 3, 2, 1, 3][k]] + (12 if k in (2, 5) else 0)433 place(buf, piano(midi(note), 7.0, rng.uniform(0.5, 0.85), 0.85), base + at + rng.uniform(-0.1, 0.1), 1.0, rng.uniform(-0.5, 0.5))434 for note in chord[:3]:435 place(buf, pad(midi(note), 22.0, rng, 7.0, 8.0, voices=3, rolloff=2.2), base - 2.0, 0.09, rng.uniform(-0.5, 0.5))436 return finish(reverb(buf, rng, 4.0, 0.42, 5500), -4.0)437438439# ---------------------------------------------------------------- interface effects440441def fx_tap(rng):442 t = tvec(0.05)443 return finish(fade(np.sin(TAU * (1500 - 6000 * t) * t) * np.exp(-t * 90), 0.0005, 0.01), -9.0)444445446def fx_correct(rng):447 buf = np.zeros(int(0.5 * SR))448 place(buf, bell(midi(84), 0.3, 1.0)[: int(0.3 * SR)], 0.0)449 place(buf, bell(midi(91), 0.38, 1.0)[: int(0.38 * SR)], 0.1)450 return finish(fade(buf, 0.001, 0.05), -6.0)451452453def fx_wrong(rng):454 buf = np.zeros(int(0.42 * SR))455 for i, note in enumerate([58, 55]):456 place(buf, sine(midi(note), 0.17, 0.005, 0.06, ((1, 1.0), (2, 0.4), (3, 0.5), (5, 0.2))), i * 0.15)457 return finish(fade(buf, 0.001, 0.05), -7.0)458459460def fx_complete(rng):461 buf = np.zeros(int(1.0 * SR))462 for i, note in enumerate([72, 76, 79, 84]):463 place(buf, bell(midi(note), 0.6, 0.8 + 0.07 * i)[: int((0.95 - i * 0.09) * SR)], i * 0.09)464 return finish(fade(buf, 0.001, 0.2), -5.0)465466467ALARMS = {468 "classic-alarm": classic_alarm, "gentle-piano": gentle_piano, "ambient-rise": ambient_rise,469 "soft-electronic": soft_electronic, "energetic-wake": energetic_wake, "minimal-tones": minimal_tones,470 "forest-birds": forest_birds, "ocean-bell": ocean_bell, "rain-chime": rain_chime,471}472SCAPES = {473 "ambient-sunrise": scape_ambient_sunrise, "rain": scape_rain, "forest": scape_forest,474 "ocean": scape_ocean, "piano-drift": scape_piano_drift,475}476EFFECTS = {"tap": fx_tap, "correct": fx_correct, "wrong": fx_wrong, "complete": fx_complete}477478479# ---------------------------------------------------------------- encoding and checks480481def write_wav(path, sig, rng):482 data = sig.T if sig.ndim == 2 else sig483 dither = (rng.random(data.shape) - rng.random(data.shape)) / 32768 # TPDF dither484 pcm = np.clip(np.round((data + dither) * 32767), -32768, 32767).astype("<i2")485 with wave.open(path, "wb") as w:486 w.setnchannels(2 if sig.ndim == 2 else 1)487 w.setsampwidth(2)488 w.setframerate(SR)489 w.writeframes(pcm.tobytes())490491492def read_any(path):493 """Decodes any bundled file to float samples (channels, frames) through afconvert."""494 with tempfile.TemporaryDirectory() as tmp:495 wav = os.path.join(tmp, "d.wav")496 subprocess.run(["afconvert", "-f", "WAVE", "-d", "LEI16", path, wav], check=True)497 with wave.open(wav, "rb") as w:498 raw = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float64) / 32768499 return raw.reshape(-1, w.getnchannels()).T, w.getframerate()500501502def encode(sig, target, kind, rng):503 with tempfile.TemporaryDirectory() as tmp:504 wav = os.path.join(tmp, "s.wav")505 write_wav(wav, sig, rng)506 if kind == "alarm":507 args = ["afconvert", "-f", "caff", "-d", "ima4", wav, target]508 elif kind == "scape":509 args = ["afconvert", "-f", "m4af", "-d", "aac", "-b", "112000", "-q", "127", wav, target]510 else:511 args = ["afconvert", "-f", "caff", "-d", "LEI16", wav, target]512 subprocess.run(args, check=True)513514515def db(x):516 return 20 * math.log10(max(x, 1e-9))517518519def check():520 """Measures every bundled file after decoding: duration, peak, RMS, clipped samples and loop seam."""521 print(f"{'file':30} {'ch':>2} {'sec':>6} {'peak dB':>8} {'rms dB':>7} {'clip':>5} {'seam':>6} {'kB':>6}")522 total, ok = 0, True523 names = [f"{k}.caf" for k in ALARMS] + [f"scape-{k}.m4a" for k in SCAPES] + [f"fx-{k}.caf" for k in EFFECTS]524 for name in names:525 path = os.path.join(OUT, name)526 if not os.path.exists(path):527 print(f"{name:30} MISSING"); ok = False; continue528 sig, rate = read_any(path)529 peak, rms = np.max(np.abs(sig)), math.sqrt(np.mean(sig ** 2))530 clipped = int(np.sum(np.abs(sig) >= 0.9999))531 # Seam: jump between the last and first sample, relative to the largest sample-to-sample step inside the file.532 step = np.max(np.abs(np.diff(sig, axis=-1))) + 1e-9533 seam = float(np.max(np.abs(sig[:, 0] - sig[:, -1])) / step)534 size = os.path.getsize(path); total += size535 print(f"{name:30} {sig.shape[0]:>2} {sig.shape[1] / rate:>6.2f} {db(peak):>8.2f} {db(rms):>7.2f} {clipped:>5} {seam:>6.2f} {size / 1024:>6.0f}")536 if rate != SR or clipped > 0 or rms < 1e-3:537 ok = False538 print(f"total {total / 1e6:.2f} MB -> {'OK' if ok else 'PROBLEM'}")539 return ok540541542def main():543 args = [a for a in sys.argv[1:] if not a.startswith("-")]544 if "--check" in sys.argv:545 sys.exit(0 if check() else 1)546 os.makedirs(OUT, exist_ok=True)547 jobs = [(k, f, "alarm", f"{k}.caf") for k, f in ALARMS.items()]548 jobs += [(k, f, "scape", f"scape-{k}.m4a") for k, f in SCAPES.items()]549 jobs += [(k, f, "fx", f"fx-{k}.caf") for k, f in EFFECTS.items()]550 for index, (key, render, kind, name) in enumerate(jobs):551 if args and key not in args and name not in args:552 continue553 rng = np.random.default_rng(20261121 + index) # fixed seed per file: identical output on every run554 sig = render(rng)555 encode(sig, os.path.join(OUT, name), kind, rng)556 print(f"wrote {name} ({sig.shape[-1] / SR:.2f} s)")557 sys.exit(0 if check() else 1)558559560if __name__ == "__main__":561 main()562