Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date. Images, audio, models and binaries go through Git LFS (.gitattributes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
214
Tools/audio/master.py
Normal file
214
Tools/audio/master.py
Normal file
@ -0,0 +1,214 @@
|
||||
"""Master ElevenLabs raw candidates into final game WAVs in Assets/Audio.
|
||||
|
||||
Tools:
|
||||
one-shot clean-up (trim lead silence so the transient is at ~2 ms, trim tail, fade, normalize),
|
||||
onset slicing of sequences (pops, footsteps, thuds), seamless crossfade loops,
|
||||
beat-aligned music loops (tempo from onset autocorrelation, loop point refined by
|
||||
cross-correlation so the wrap lands on the same beat phase).
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import wave
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
SR = 44100
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
RAW = os.path.join(HERE, "eleven_raw")
|
||||
OUT = os.path.join(os.path.dirname(os.path.dirname(HERE)), "Assets", "Audio")
|
||||
|
||||
|
||||
def load(path):
|
||||
if path.endswith(".mp3"):
|
||||
wav = path[:-4] + "_dec.wav"
|
||||
if not os.path.exists(wav):
|
||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", path, "-ar", str(SR), "-ac", "2", wav], check=True)
|
||||
path = wav
|
||||
with wave.open(path) as w:
|
||||
ch, n = w.getnchannels(), w.getnframes()
|
||||
assert w.getframerate() == SR, path
|
||||
x = np.frombuffer(w.readframes(n), dtype=np.int16).astype(np.float64) / 32768
|
||||
return x.reshape(-1, 2) if ch == 2 else x
|
||||
|
||||
|
||||
def raw(name):
|
||||
return load(os.path.join(RAW, name))
|
||||
|
||||
|
||||
def db(v):
|
||||
return 10 ** (v / 20)
|
||||
|
||||
|
||||
def mono(x):
|
||||
return x if x.ndim == 1 else x.mean(axis=1)
|
||||
|
||||
|
||||
def envelope(x, ms=2.0):
|
||||
a = np.abs(mono(x))
|
||||
k = max(1, int(ms * SR / 1000))
|
||||
from scipy.ndimage import uniform_filter1d
|
||||
return uniform_filter1d(a, k, mode="nearest")
|
||||
|
||||
|
||||
def highpass(x, f=35):
|
||||
sos = signal.butter(2, f, btype="high", fs=SR, output="sos")
|
||||
return signal.sosfilt(sos, x, axis=0)
|
||||
|
||||
|
||||
def lowpass(x, f):
|
||||
sos = signal.butter(2, f, btype="low", fs=SR, output="sos")
|
||||
return signal.sosfilt(sos, x, axis=0)
|
||||
|
||||
|
||||
def fade(x, fin_ms=1.0, fout_ms=15.0):
|
||||
x = x.copy()
|
||||
a, b = int(fin_ms * SR / 1000), int(fout_ms * SR / 1000)
|
||||
shp = (lambda v: v[:, None]) if x.ndim == 2 else (lambda v: v)
|
||||
if a:
|
||||
x[:a] *= shp(np.linspace(0, 1, a))
|
||||
if b:
|
||||
x[-b:] *= shp(np.linspace(1, 0, b) ** 2)
|
||||
return x
|
||||
|
||||
|
||||
def clean(x, lead_ms=2.0, start_db=-30, tail_db=-50, max_len=None, fout_ms=20):
|
||||
x = highpass(x)
|
||||
env = envelope(x, 1.0)
|
||||
pk = env.max()
|
||||
on = int(np.argmax(env > pk * db(start_db)))
|
||||
on = max(0, on - int(lead_ms * SR / 1000))
|
||||
x = x[on:]
|
||||
env = env[on:]
|
||||
above = np.where(env > pk * db(tail_db))[0]
|
||||
end = above[-1] + int(0.01 * SR) if len(above) else len(x)
|
||||
if max_len:
|
||||
end = min(end, int(max_len * SR))
|
||||
return fade(x[:end], 1.0 if lead_ms > 0.5 else 0.0, fout_ms)
|
||||
|
||||
|
||||
def normalize(x, peak_db=-3.0):
|
||||
return x * (db(peak_db) / (np.abs(x).max() + 1e-12))
|
||||
|
||||
|
||||
def write(name, x, peak_db=-3.0, ext=".wav"):
|
||||
x = normalize(x, peak_db) if peak_db is not None else x
|
||||
data = np.clip(x * 32767, -32768, 32767).astype(np.int16)
|
||||
path = os.path.join(OUT, name + ext)
|
||||
with wave.open(path, "wb") as w:
|
||||
w.setnchannels(1 if data.ndim == 1 else 2)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(SR)
|
||||
w.writeframes(data.tobytes())
|
||||
print(f" {name}{ext} {len(data) / SR:.2f}s")
|
||||
return x
|
||||
|
||||
|
||||
def onsets(x, min_gap=0.12, rel_db=-14):
|
||||
env = envelope(x, 2.0)
|
||||
pk = env.max()
|
||||
thr = pk * db(rel_db)
|
||||
d = np.diff(env, prepend=0)
|
||||
cand = np.where((env > thr) & (d > 0))[0]
|
||||
res = []
|
||||
last = -10 ** 9
|
||||
for c in cand:
|
||||
if c - last > min_gap * SR:
|
||||
res.append(c)
|
||||
last = c
|
||||
return res
|
||||
|
||||
|
||||
def slice_seq(x, max_len=0.3, min_gap=0.12, rel_db=-14):
|
||||
x = highpass(x)
|
||||
ons = onsets(x, min_gap, rel_db)
|
||||
segs = []
|
||||
for i, o in enumerate(ons):
|
||||
s = max(0, o - int(0.004 * SR))
|
||||
e = ons[i + 1] - int(0.006 * SR) if i + 1 < len(ons) else len(x)
|
||||
e = min(e, s + int(max_len * SR))
|
||||
seg = x[s:e]
|
||||
env = envelope(seg)
|
||||
segs.append((seg, env.max(), o / SR))
|
||||
return segs
|
||||
|
||||
|
||||
def loop_xfade(x, xf=0.5):
|
||||
n = int(xf * SR)
|
||||
body = x[:-n].copy()
|
||||
tail = x[-n:]
|
||||
w = np.linspace(0, 1, n)
|
||||
if x.ndim == 2:
|
||||
w = w[:, None]
|
||||
body[:n] = body[:n] * np.sqrt(w) + tail * np.sqrt(1 - w)
|
||||
return body
|
||||
|
||||
|
||||
def onset_strength(x, hop=512):
|
||||
m = mono(x)
|
||||
f, t, Z = signal.stft(m, SR, nperseg=2048, noverlap=2048 - hop)
|
||||
mag = np.log1p(np.abs(Z) * 100)
|
||||
flux = np.maximum(0, np.diff(mag, axis=1)).sum(axis=0)
|
||||
flux = np.concatenate([[0], flux])
|
||||
return flux - flux.mean(), SR / hop
|
||||
|
||||
|
||||
def tempo(x, lo=70, hi=150):
|
||||
oss, fps = onset_strength(x)
|
||||
ac = np.correlate(oss, oss, mode="full")[len(oss) - 1:]
|
||||
lags = np.arange(len(ac)) / fps
|
||||
valid = (lags > 60 / hi) & (lags < 60 / lo)
|
||||
i = np.argmax(ac * valid)
|
||||
# parabolic refinement
|
||||
y0, y1, y2 = ac[i - 1], ac[i], ac[i + 1]
|
||||
off = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)
|
||||
period = (i + off) / fps
|
||||
return 60 / period, period
|
||||
|
||||
|
||||
def music_loop(x, start_hint=4.0, tail_trim=6.0, xf_beats=1.0):
|
||||
"""Cut a beat-aligned seamless loop out of a full music render."""
|
||||
bpm, beat = tempo(x)
|
||||
bar = beat * 4
|
||||
oss, fps = onset_strength(x)
|
||||
# loop start: strongest onset within one bar after the hint (likely a downbeat)
|
||||
a, b = int(start_hint * fps), int((start_hint + bar) * fps)
|
||||
start = (a + np.argmax(oss[a:b])) / fps
|
||||
usable_end = len(x) / SR - tail_trim
|
||||
bars = int((usable_end - start) / bar)
|
||||
end_guess = start + bars * bar
|
||||
# refine end so the onset pattern around it best matches the one at the start (same beat phase)
|
||||
oss_f, fps_f = onset_strength(x, hop=128)
|
||||
pre, post = int(bar * 1.0 * fps_f), int(bar * 1.5 * fps_f)
|
||||
win = pre + post
|
||||
i0 = int(start * fps_f)
|
||||
ref = oss_f[max(0, i0 - pre):i0 + post]
|
||||
win = len(ref)
|
||||
best, best_e = -1e9, end_guess
|
||||
for d in np.arange(-0.25 * beat, 0.25 * beat, 1 / fps_f):
|
||||
j = int(round((end_guess + d) * fps_f))
|
||||
segf = oss_f[j - (i0 - max(0, i0 - pre)):j - (i0 - max(0, i0 - pre)) + win]
|
||||
if len(segf) < win:
|
||||
continue
|
||||
c = np.dot(ref, segf) / (np.linalg.norm(ref) * np.linalg.norm(segf) + 1e-12)
|
||||
if c > best:
|
||||
best, best_e = c, end_guess + d
|
||||
# sample-accurate touch-up with waveform correlation in a +-3 ms window
|
||||
ref_w = mono(x)[int(start * SR): int(start * SR) + int(0.2 * SR)]
|
||||
bw, be = -1e9, best_e
|
||||
for d in np.arange(-0.003, 0.003, 1 / SR):
|
||||
e = int((best_e + d) * SR)
|
||||
sw = mono(x)[e:e + len(ref_w)]
|
||||
c = np.dot(ref_w, sw) / (np.linalg.norm(ref_w) * np.linalg.norm(sw) + 1e-12)
|
||||
if c > bw:
|
||||
bw, be = c, best_e + d
|
||||
best_e = be
|
||||
s, e = int(start * SR), int(best_e * SR)
|
||||
n = int(xf_beats * beat * SR)
|
||||
loop = x[s:e].copy()
|
||||
w = np.linspace(0, 1, n)[:, None]
|
||||
# head of loop blends from the continuation after e into the true start
|
||||
loop[:n] = x[s:s + n] * np.sqrt(w) + x[e:e + n] * np.sqrt(1 - w)
|
||||
print(f" onset-match {best:.3f}, wave-match {bw:.3f}")
|
||||
print(f" music: {bpm:.1f} bpm, start {start:.2f}s, {bars} bars, end {best_e:.3f}s (match {best:.3f}), len {len(loop) / SR:.1f}s")
|
||||
return loop
|
||||
Reference in New Issue
Block a user