"""Diesel bus engine loops for the Tessel Tours bus (a friend's idea, 2026-10-15). SL can't pitch-shift a sound, so we render one seamless loop per rev band and the script swaps between them by speed. Run with local/hear-venv python: gen_engine.py OUTDIR -> engine_idle.wav, engine_low.wav, engine_mid.wav, engine_high.wav (44.1 kHz mono) Each loop is a whole number of engine cycles so it repeats without a click. Claude Opus 5.5 (as Tessel). """ import sys, wave, pathlib import numpy as np SR = 44100 CYL = 6 BANDS = {"idle": 650, "low": 1050, "mid": 1550, "high": 2150} # rpm LOOP_S = 2.0 def onepole_lp(x, fc): a = np.exp(-2 * np.pi * fc / SR) y = np.empty_like(x) acc = 0.0 for i, v in enumerate(x): acc = (1 - a) * v + a * acc y[i] = acc return y def render(rpm, seed): rng = np.random.default_rng(seed) fire_hz = rpm / 60 * CYL / 2 cycle_hz = rpm / 60 / 2 # one full 4-stroke cycle = CYL firings n_cycles = max(1, round(LOOP_S * cycle_hz)) n = int(round(n_cycles / cycle_hz * SR)) period = n / (n_cycles * CYL) # samples per firing, exact over the loop fire_hz = n_cycles * CYL * SR / n # snap so the rumble has whole cycles per loop t = np.arange(n) / SR out = np.zeros(n) # per-cylinder character, fixed so each cycle repeats exactly -> seamless cyl_gain = 1 + 0.18 * rng.standard_normal(CYL) cyl_jit = 0.06 * period * rng.standard_normal(CYL) pulse_len = int(min(period * 1.6, 0.05 * SR)) k = np.arange(pulse_len) env = np.exp(-k / (pulse_len * 0.22)) * (1 - np.exp(-k / 18)) thump_f = 55 + rpm * 0.02 bursts = [onepole_lp(rng.standard_normal(pulse_len), 900 + rpm * 0.6) for _ in range(CYL)] for j in range(n_cycles * CYL): c = j % CYL start = j * period + cyl_jit[c] s = int(start) % n pulse = env * (0.55 * np.sin(2 * np.pi * thump_f * k / SR) + 0.9 * bursts[c]) * cyl_gain[c] idx = (s + k) % n # wrap into the loop start np.add.at(out, idx, pulse) # rumble: firing fundamental + harmonics, and a turbo whine rising with revs rumble = sum(a * np.sin(2 * np.pi * fire_hz * h * t) for h, a in ((0.5, 0.25), (1, 0.35), (2, 0.12), (3, 0.05))) out += rumble turbo_f = 1800 + (rpm - 600) * 1.4 turbo_f = round(turbo_f * n / SR) * SR / n # whole cycles per loop out += (0.012 + 0.03 * (rpm - 650) / 1500) * np.sin(2 * np.pi * turbo_f * t) # gentle low-pass for "behind a bus body", then normalise out = onepole_lp(np.concatenate([out, out]), 2600)[n:] # filter in steady state: seamless out -= out.mean() out /= np.max(np.abs(out)) + 1e-9 return (out * 0.8 * 32767).astype(np.int16) def main(outdir): d = pathlib.Path(outdir) d.mkdir(parents=True, exist_ok=True) for i, (name, rpm) in enumerate(BANDS.items()): pcm = render(rpm, 7 + i) p = d / f"engine_{name}.wav" with wave.open(str(p), "wb") as w: w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR) w.writeframes(pcm.tobytes()) print(p, f"{len(pcm)/SR:.2f}s", f"{rpm} rpm") if __name__ == "__main__": main(sys.argv[1] if len(sys.argv) > 1 else ".")