#!/usr/bin/env python3 """ Dark, smoky British female TTS vocal, locked to a tempo grid (default 140 BPM). "When you change the way you look at things, the things you look at change." Pipeline: Piper (local ONNX TTS, en_GB "cori" high-quality British female voice) -> rubberband: time-fit each phrase to the bar grid + pitch down (deeper, darker) -> smoky chain: high-pass, low warmth, tape saturation, dark roll-off, compression -> tempo-synced ping-pong delay (dotted 8th) + dark plate reverb Requires: python3 with numpy, scipy, soundfile, piper-tts; the `rubberband` CLI. Voice files en_GB-cori-high.onnx + .onnx.json from https://huggingface.co/rhasspy/piper-voices/tree/main/en/en_GB/cori/high Usage: python3 make_vocal.py --voice /path/to/en_GB-cori-high.onnx [--bpm 140] [--pitch -2.5] Writes: when_you_change_bpm.wav (wet, 8 bars) and ..._dry.wav (no delay/reverb) """ import argparse import os import subprocess import sys import tempfile import numpy as np import soundfile as sf from scipy import signal from scipy.signal import fftconvolve HERE = os.path.dirname(os.path.abspath(__file__)) SR = 48000 PHRASES = [ # text, start bar (0-based), max bars it may occupy ("When you change the way you look at things,", 0, 2), ("the things you look at change.", 2, 2), ] BARS_TOTAL = 8 def synth(voice, text, length_scale, noise_scale=0.55, noise_w=0.7): """Piper TTS via its CLI -> (float samples, sample rate). Lower noise = calmer, more even delivery.""" with tempfile.TemporaryDirectory() as d: out = os.path.join(d, "t.wav") subprocess.run([sys.executable, "-m", "piper", "-m", voice, "-f", out, "--length-scale", str(length_scale), "--noise-scale", str(noise_scale), "--noise-w-scale", str(noise_w)], input=text.encode(), check=True, capture_output=True) x, sr = sf.read(out) return x.astype(np.float64), sr def trim(x, thresh=0.01): idx = np.where(np.abs(x) > thresh * np.max(np.abs(x)))[0] return x[idx[0]:idx[-1] + 1] def rubberband(x, sr, ratio, semitones): """Time-stretch to `ratio` x the length and pitch-shift (formants move with pitch).""" with tempfile.TemporaryDirectory() as d: a, b = os.path.join(d, "in.wav"), os.path.join(d, "out.wav") sf.write(a, x, sr, subtype="FLOAT") subprocess.run(["rubberband", "-q", "-t", "%.6f" % ratio, "-p", "%.3f" % semitones, a, b], check=True) y, sr2 = sf.read(b) return y def lp(x, hz, order=2): return signal.sosfilt(signal.butter(order, hz, "low", fs=SR, output="sos"), x) def hp(x, hz, order=2): return signal.sosfilt(signal.butter(order, hz, "high", fs=SR, output="sos"), x) def compress(x, thresh_db=-22.0, ratio=3.0, attack=0.005, release=0.12): a, r = np.exp(-1 / (attack * SR)), np.exp(-1 / (release * SR)) env = np.zeros_like(x) e = 0.0 ax = np.abs(x) for i in range(len(x)): e = a * e + (1 - a) * ax[i] if ax[i] > e else r * e + (1 - r) * ax[i] env[i] = e db = 20 * np.log10(np.maximum(env, 1e-6)) over = np.maximum(db - thresh_db, 0) gain = 10 ** (-(over * (1 - 1 / ratio)) / 20) return x * gain def smoky(x): x = hp(x, 85) x = x + 0.5 * lp(x, 230) # chesty low warmth x = x + 0.35 * (np.tanh(2.2 * x) / np.tanh(2.2) - x) # tape-ish saturation (35 % blend) x = lp(x, 6200, 4) # dark roll-off: no air, no sizzle x = compress(x) return x def plate(x, rt60=3.2, predelay=0.03, seed=7): """Dark stereo plate: decaying noise, progressively low-passed.""" rng = np.random.default_rng(seed) n = int(rt60 * 1.1 * SR) t = np.arange(n) / SR outs = [] for _ in range(2): noise = rng.standard_normal(n) ir = np.zeros(n) for lo, hi, w in ((0.0, 0.4, 3800), (0.4, 1.2, 2400), (1.2, 99, 1500)): m = (t >= lo) & (t < hi) ir += lp(noise, w) * m ir *= np.exp(-6.91 * t / rt60) ir = np.concatenate([np.zeros(int(predelay * SR)), ir]) outs.append(fftconvolve(x, ir / np.sqrt(np.sum(ir ** 2)))) n = max(len(o) for o in outs) return np.stack([np.pad(o, (0, n - len(o))) for o in outs], axis=1) def pingpong(x, beat, feedback=0.38, taps=6): """Dotted-8th (0.75 beat) ping-pong delay, each repeat darker.""" step = int(round(0.75 * beat * SR)) out = np.zeros((len(x) + step * taps + 1, 2)) sig = x.copy() for k in range(1, taps + 1): sig = lp(sig, 2400) * feedback out[k * step:k * step + len(sig), k % 2] += sig return out def mix_in(buf, x, at): n = min(len(x), len(buf) - at) buf[at:at + n] += x[:n] def main(): ap = argparse.ArgumentParser() ap.add_argument("--voice", required=True, help="Piper voice .onnx (the .onnx.json must sit next to it)") ap.add_argument("--bpm", type=float, default=140.0) ap.add_argument("--pitch", type=float, default=-2.5, help="semitones (negative = deeper)") ap.add_argument("--length-scale", type=float, default=1.25, help="Piper pacing (>1 = slower, more deliberate)") ap.add_argument("--out", default=HERE) args = ap.parse_args() beat = 60.0 / args.bpm bar = 4 * beat total = int(BARS_TOTAL * bar * SR) dry = np.zeros(total + SR * 4) for text, start_bar, max_bars in PHRASES: target = max_bars * bar - 1.5 * beat # leave a breath before the next phrase ls = args.length_scale for _ in range(2): # let Piper itself pace the phrase (better prosody than post-stretching) x, sr = synth(args.voice, text, ls) x = signal.resample_poly(trim(x), SR, sr) natural = len(x) / SR ls *= min(1.9, max(0.8, target / natural)) ** 0.9 x, sr = synth(args.voice, text, ls) x = signal.resample_poly(trim(x), SR, sr) natural = len(x) / SR ratio = min(1.35, max(0.8, target / natural)) # keep the delivery natural y = rubberband(x, SR, ratio, args.pitch) y = smoky(y) mix_in(dry, y, int(round(start_bar * bar * SR))) print("%-46s natural %.2fs -> x%.2f = %.2fs (bar %d, grid slot %.2fs)" % (text[:46], natural, ratio, len(y) / SR, start_bar + 1, max_bars * bar)) dry = dry[:total + SR * 4] delay = pingpong(dry, beat) verb = plate(dry) n = max(len(dry), len(delay), len(verb)) wet = np.zeros((n, 2)) wet[:len(dry)] += dry[:, None] * 0.9 wet[:len(delay)] += delay * 0.28 wet[:len(verb)] += verb * 0.55 wet = wet[:int(BARS_TOTAL * bar * SR)] # fade the last 1.5 beats so the tail ends cleanly on the grid fade = int(1.5 * beat * SR) wet[-fade:] *= np.linspace(1, 0, fade)[:, None] dry2 = np.repeat(dry[:len(wet), None], 2, axis=1) for name, sig in (("when_you_change_%dbpm.wav" % args.bpm, wet), ("when_you_change_%dbpm_dry.wav" % args.bpm, dry2)): sig = sig / np.max(np.abs(sig)) * 10 ** (-1 / 20) # peak -1 dBFS sf.write(os.path.join(args.out, name), sig, SR, subtype="PCM_24") print("wrote", os.path.join(args.out, name), "%.3fs" % (len(sig) / SR)) if __name__ == "__main__": main()