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>
432 lines
21 KiB
Python
432 lines
21 KiB
Python
"""GRASS CUTTER farm sounds: eleven_raw/farm*_ candidates (eleven_batch_farm.sh) -> Tools/audio/final_farm/.
|
|
|
|
Writes nothing into Assets: Unity may be building there. Assets/Audio is only read, to match levels to the file each
|
|
sound replaces. Trims with master.clean, loops by an aligned tail-into-head crossfade (the last sample of a loop runs
|
|
straight on into the first), measures everything at the end.
|
|
|
|
Usage: python finalize_farm.py [shots] [loops] [ambience] [music] [check] (default: all of them)
|
|
"""
|
|
import glob
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import wave
|
|
|
|
import numpy as np
|
|
from scipy import signal
|
|
|
|
import master as M
|
|
from finalize import compress
|
|
from master import SR
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
AUDIO = os.path.join(os.path.dirname(os.path.dirname(HERE)), "Assets", "Audio")
|
|
FINAL = os.path.join(HERE, "final_farm")
|
|
M.OUT = FINAL # master.write defaults to Assets/Audio
|
|
assert "Assets" not in os.path.relpath(M.OUT, HERE)
|
|
os.makedirs(FINAL, exist_ok=True)
|
|
|
|
|
|
def dbv(v):
|
|
return 20 * np.log10(v + 1e-12)
|
|
|
|
|
|
def active_rms(x):
|
|
"""RMS of the part that sounds: 10 ms blocks within 20 dB of the loudest one."""
|
|
m = M.mono(x)
|
|
k = int(0.01 * SR)
|
|
e = np.sqrt(np.convolve(m ** 2, np.ones(k) / k, "same"))
|
|
return np.sqrt(np.mean(m[e > e.max() * 0.1] ** 2))
|
|
|
|
|
|
def lufs(path):
|
|
"""Integrated loudness: RMS cannot compare low wind with broadband noise, ears and this can."""
|
|
out = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", path, "-af", "ebur128", "-f", "null", "-"],
|
|
capture_output=True, text=True).stderr
|
|
return float(re.findall(r"I:\s+(-?[\d.]+) LUFS", out)[-1])
|
|
|
|
|
|
def to_lufs(name, x, want):
|
|
"""Write, measure, and write again with the gain that lands on `want`."""
|
|
tmp = os.path.join(HERE, "eleven_raw", "_lufs_probe.wav")
|
|
data = np.clip(x * 32767, -32768, 32767).astype(np.int16)
|
|
with wave.open(tmp, "wb") as w:
|
|
w.setnchannels(x.ndim)
|
|
w.setsampwidth(2)
|
|
w.setframerate(SR)
|
|
w.writeframes(data.tobytes())
|
|
y = x * M.db(want - lufs(tmp))
|
|
os.remove(tmp)
|
|
ceil = M.db(-1)
|
|
if np.abs(y).max() > ceil:
|
|
y = ceil * np.tanh(y / ceil)
|
|
M.write(name, y, None)
|
|
|
|
|
|
def old_level(name):
|
|
return dbv(active_rms(M.load(os.path.join(AUDIO, name + ".wav"))))
|
|
|
|
|
|
def put(name, x, ref, ceiling=-1.0):
|
|
"""Write `name` at the level of `ref` (an old file name, or a level in dB), softly limited under `ceiling`."""
|
|
want = ref if isinstance(ref, (int, float)) else old_level(ref)
|
|
ceil = M.db(ceiling)
|
|
g = M.db(want) / (active_rms(x) + 1e-12)
|
|
g = min(g, ceil * M.db(4) / (np.abs(x).max() + 1e-12)) # never push a transient more than 4 dB into the limiter
|
|
y = x * g
|
|
if np.abs(y).max() > ceil:
|
|
y = ceil * np.tanh(y / ceil)
|
|
M.write(name, y, None)
|
|
|
|
|
|
def r(name, hp=40):
|
|
"""Raw candidate, mono, with the DC and rumble below `hp` taken off."""
|
|
return M.highpass(M.mono(M.raw(name + ".wav")), hp)
|
|
|
|
|
|
def seg(x, a, b):
|
|
return x[int(a * SR): int(b * SR)]
|
|
|
|
|
|
def thud(sec, f0=70.0, decay=0.08):
|
|
t = np.arange(int(sec * SR)) / SR
|
|
f = f0 * (1 + 0.6 * np.exp(-t / 0.02))
|
|
return np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t / decay)
|
|
|
|
|
|
def under(x, low, amount):
|
|
"""Lay a thud under a sound that came back without weight."""
|
|
x = x.copy()
|
|
n = min(len(x), len(low))
|
|
x[:n] += low[:n] * amount * np.abs(x).max()
|
|
return x
|
|
|
|
|
|
def around_peak(x, pre, post):
|
|
p = int(np.argmax(M.envelope(x, 8.0)))
|
|
return x[max(0, p - int(pre * SR)): p + int(post * SR)]
|
|
|
|
|
|
def steps(names, count, max_len=0.26):
|
|
"""The cleanest separate footsteps out of walking takes: strong, and close to one another in level."""
|
|
found = []
|
|
for n in names:
|
|
found += [s for s, pk, t in M.slice_seq(r(n, 60), max_len=max_len, min_gap=0.4, rel_db=-14)]
|
|
found = [M.clean(s, start_db=-24, tail_db=-40, max_len=max_len, fout_ms=40) for s in found if len(s) > 0.1 * SR]
|
|
found = [s for s in found if len(s) > 0.09 * SR]
|
|
lv = np.array([dbv(active_rms(s)) for s in found])
|
|
order = np.argsort(np.abs(lv - np.median(lv)))
|
|
return [found[i] for i in order[:count]]
|
|
|
|
|
|
def shots():
|
|
# (file, raw take, level of which old file, clean() settings)
|
|
T = [
|
|
("snip", "farm_snip_5", "snip", dict(start_db=-24, tail_db=-40, max_len=0.17, fout_ms=30)),
|
|
("shears_snip_1", "farm_snip_2", "snip", dict(start_db=-24, tail_db=-40, max_len=0.17, fout_ms=30)),
|
|
("shears_snip_2", "farm_snip_1", "snip", dict(start_db=-24, tail_db=-40, max_len=0.17, fout_ms=30)),
|
|
("scythe_swing_1", "farm_scythe_0", "throw_whoosh", dict(start_db=-32, tail_db=-44, max_len=0.55, lead_ms=0, fout_ms=90)),
|
|
("scythe_swing_2", "farm_scythe_5", "throw_whoosh", dict(start_db=-32, tail_db=-44, max_len=0.55, lead_ms=0, fout_ms=90)),
|
|
("scythe_swing_3", "farm_scythe_3", "throw_whoosh", dict(start_db=-32, tail_db=-44, max_len=0.55, lead_ms=0, fout_ms=90)),
|
|
("cash_register", "farm_cash_1", "cash_register", dict(tail_db=-50, max_len=1.45, fout_ms=250)),
|
|
("coin_tick", "farm_coin_tick_1", "coin_tick", dict(start_db=-20, tail_db=-36, max_len=0.09, fout_ms=25)),
|
|
("ui_click", "farm_ui_click_1", "ui_click", dict(start_db=-20, tail_db=-44, max_len=0.14, fout_ms=30)),
|
|
("ui_hover", "farm_ui_hover_1", "ui_hover", dict(start_db=-20, tail_db=-34, max_len=0.06, fout_ms=20)),
|
|
("ui_open", "farm_ui_open_0", "ui_open", dict(start_db=-30, tail_db=-46, max_len=0.67, fout_ms=120)),
|
|
("ui_close", "farm_ui_close_0", "ui_close", dict(start_db=-30, tail_db=-46, max_len=0.6, fout_ms=120)),
|
|
("perk_unlock", "farm_perk_0", "perk_unlock", dict(tail_db=-48, max_len=1.8, fout_ms=300)),
|
|
("milestone", "farm_milestone_0", "milestone", dict(tail_db=-50, max_len=2.8, fout_ms=400)),
|
|
("land", "farm2_land_0", "land", dict(start_db=-30, tail_db=-44, max_len=0.38, fout_ms=60)),
|
|
("suck_stop", "farm_whiff_0", "suck_stop", dict(start_db=-30, tail_db=-44, max_len=0.7, lead_ms=0, fout_ms=80)),
|
|
("scoop", "farm_scoop_0", "scoop", dict(start_db=-26, tail_db=-40, max_len=0.55, lead_ms=0, fout_ms=90)),
|
|
("gulp", "farm_gulp_0", "gulp", dict(start_db=-24, tail_db=-38, max_len=0.25, fout_ms=50)),
|
|
("press_squash", "farm_press_squash_0", "press_squash", dict(start_db=-30, tail_db=-46, max_len=0.9, fout_ms=60)),
|
|
("barrel_clunk", "farm_barrel_0", "barrel_clunk", dict(start_db=-26, tail_db=-46, max_len=0.4, fout_ms=60)),
|
|
("ice_clink", "farm_brick_0", "ice_clink", dict(start_db=-26, tail_db=-46, max_len=0.4, fout_ms=60)),
|
|
("plastic_grab", "farm_grab_0", "plastic_grab", dict(start_db=-24, tail_db=-40, max_len=0.28, fout_ms=50)),
|
|
("launcher_fire", "farm_launcher_0", "launcher_fire", dict(start_db=-30, tail_db=-44, max_len=0.64, fout_ms=100)),
|
|
("splash_big", "farm_thump_big_0", "splash_big", dict(start_db=-30, tail_db=-46, max_len=1.15, fout_ms=200)),
|
|
("splitter_flip", "farm_splitter_0", "splitter_flip", dict(start_db=-26, tail_db=-44, max_len=0.25, fout_ms=40)),
|
|
("merger_clunk", "farm_merger_0", "splitter_flip", dict(start_db=-26, tail_db=-44, max_len=0.32, fout_ms=50)),
|
|
("press_thump", "farm2_press_thump_0", "compactor_crunch", dict(start_db=-30, tail_db=-46, max_len=1.0, fout_ms=150)),
|
|
("battery_full", "farm_battery_full_0", "perk_unlock", dict(start_db=-30, tail_db=-40, max_len=0.8, fout_ms=120)),
|
|
("power_low", "farm2_power_low_0", "error", dict(start_db=-30, tail_db=-44, max_len=1.6, fout_ms=250)),
|
|
("build_place", "farm2_build_place_0", "build_place", dict(start_db=-26, tail_db=-44, max_len=0.34, fout_ms=50)),
|
|
("build_remove", "farm3_build_remove_0", "build_remove", dict(start_db=-30, tail_db=-44, max_len=0.55, fout_ms=70)),
|
|
]
|
|
for out, take, ref, kw in T:
|
|
x = M.clean(r(take), **kw)
|
|
if out in ("press_squash", "ice_clink", "build_remove"): # all crack and no body: too peaky to reach their level
|
|
x = compress(x, -20, 3.0)
|
|
put(out, x, ref)
|
|
|
|
# the rest need more than a trim
|
|
for i, s in enumerate(steps(["farm2_steps_grass_0", "farm2_steps_grass_1"], 2) + steps(["farm_steps_wood_0", "farm_steps_wood_1"], 2)):
|
|
put(f"footstep_{i + 1}", s, -27.0) # the old set spans -24.7 to -31.9
|
|
put("jump", M.clean(around_peak(r("farm2_jump_0", 120), 0.08, 0.16), start_db=-24, tail_db=-36, max_len=0.22, lead_ms=0, fout_ms=60), "jump")
|
|
put("throw_whoosh", M.clean(r("farm2_whoosh_0", 150), start_db=-30, tail_db=-42, max_len=0.4, lead_ms=0, fout_ms=90), "throw_whoosh")
|
|
tick = M.clean(r("farm_build_rotate_0", 200), start_db=-20, tail_db=-34, max_len=0.05, fout_ms=15)
|
|
put("build_rotate", tick, "build_rotate")
|
|
|
|
# two knocks, the second lower: a comic "nope"
|
|
knock = M.clean(r("farm_error_0"), start_db=-24, tail_db=-40, max_len=0.17, fout_ms=40)
|
|
low = M.fade(np.interp(np.arange(0, len(knock) - 1, 1 / 1.2), np.arange(len(knock)), knock), 1, 30)
|
|
err = np.zeros(int(0.15 * SR) + len(low))
|
|
err[: len(knock)] += knock
|
|
err[int(0.15 * SR):] += low * 0.9
|
|
put("error", err, "error")
|
|
|
|
# a sack thumping full, then the little bell that says so
|
|
sack = M.clean(around_peak(r("farm_scoop_0", 80), 0.02, 0.22), start_db=-24, tail_db=-40, max_len=0.24, fout_ms=60)
|
|
bell = seg(r("farm2_tank_full_0", 300), 0.58, 1.18)
|
|
full = np.zeros(int(0.1 * SR) + len(bell))
|
|
bell = M.fade(bell, 2, 200)
|
|
full[int(0.1 * SR):] += bell / np.abs(bell).max() * 0.8
|
|
full[: len(sack)] += sack / np.abs(sack).max()
|
|
put("tank_full", compress(full, -20, 3.0), "tank_full")
|
|
|
|
# takes that came back all rustle and no weight
|
|
put("compactor_crunch", under(M.clean(r("farm_compactor_0"), start_db=-26, tail_db=-44, max_len=0.82, fout_ms=120), thud(0.3, 60, 0.09), 0.8), "compactor_crunch")
|
|
put("cargo_load", under(M.clean(r("farm2_cargo_load_0"), start_db=-30, tail_db=-44, max_len=0.6, fout_ms=120), thud(0.3, 75, 0.07), 0.7), "cargo_load")
|
|
put("splash_small", under(M.clean(r("farm2_thump_small_0"), start_db=-30, tail_db=-40, max_len=0.55, fout_ms=120), thud(0.3, 85, 0.06), 0.6), "splash_small")
|
|
|
|
|
|
def find_join(x, a, b, xf, search=0.3):
|
|
"""End point near b whose next xf seconds best match the xf seconds at a, so the crossfade is between alike sounds."""
|
|
m = M.mono(x)
|
|
n = int(xf * SR)
|
|
head = m[a: a + n]
|
|
lo = max(a + n, b - int(search * SR))
|
|
hi = min(len(m) - n, b + int(search * SR))
|
|
if hi <= lo:
|
|
return b
|
|
c = signal.fftconvolve(m[lo: hi + n], head[::-1], "valid")
|
|
return lo + int(np.argmax(c))
|
|
|
|
|
|
def join(x, s, e, xf):
|
|
"""Head of the loop blends from what follows e into the true start, so loop[-1] runs straight into loop[0]."""
|
|
n = int(xf * SR)
|
|
w = np.linspace(0, 1, n)
|
|
if x.ndim == 2:
|
|
w = w[:, None]
|
|
y = x[s:e].copy()
|
|
y[:n] = x[s: s + n] * np.sqrt(w) + x[e: e + n] * np.sqrt(1 - w)
|
|
return y
|
|
|
|
|
|
def steady_loop(take, a, b, xf, hp=40):
|
|
x = r(take, hp)
|
|
s, e = int(a * SR), int(b * SR)
|
|
return join(x, s, find_join(x, s, e, xf), xf)
|
|
|
|
|
|
def loops():
|
|
T = [
|
|
("suck_loop", "farm2_cut_0", 0.35, 3.9, 0.4, "suck_loop"),
|
|
("grass_rustle_loop", "farm_grass_rustle_0", 0.4, 5.0, 0.5, -25.0),
|
|
("conveyor_loop", "farm2_conveyor_0", 1.4, 6.4, 0.4, "conveyor_loop"),
|
|
("machine_hum_loop", "farm_machine_hum_0", 0.3, 5.1, 0.4, "machine_hum_loop"),
|
|
("battery_hum_loop", "farm2_battery_hum_0", 0.3, 5.2, 0.4, -32.0),
|
|
("mower_engine_loop", "farm_mower_engine_0", 0.3, 7.0, 0.4, "mower_engine_loop"),
|
|
("tractor_engine_loop", "farm_tractor_engine_0", 0.3, 7.0, 0.4, "mower_engine_loop"),
|
|
("combine_engine_loop", "farm_combine_engine_0", 0.3, 7.0, 0.4, "mower_engine_loop"),
|
|
("pickup_engine_loop", "farm_pickup_engine_0", 0.3, 7.0, 0.4, "mower_engine_loop"),
|
|
("robot_mower_loop", "farm_robot_mower_0", 0.3, 3.7, 0.3, -24.0),
|
|
]
|
|
for out, take, a, b, xf, ref in T:
|
|
put(out, steady_loop(take, a, b, xf), ref)
|
|
|
|
|
|
def stereo(name):
|
|
return M.highpass(M.raw(name + ".wav"), 30)
|
|
|
|
|
|
def ambience():
|
|
# the wind take is all low swells, the first take all hiss, the birds came separately: together they make a meadow
|
|
low = stereo("farm2_wind_0")
|
|
air = M.highpass(M.lowpass(M.lowpass(stereo("farm_wind_meadow_0"), 3500), 3500), 500)
|
|
birds = M.highpass(stereo("farm2_birds_0"), 1200)
|
|
n = min(len(low), len(air), len(birds))
|
|
rms = lambda v: np.sqrt(np.mean(v ** 2))
|
|
low = low[:n] / rms(low[:n]) * M.db(-30)
|
|
air = air[:n] / rms(air[:n]) * M.db(-40)
|
|
birds = birds[:n] / np.abs(birds[:n]).max() * M.db(-25) # far away: only just over the wind
|
|
mix = low + air + birds
|
|
s, e = int(0.5 * SR), int(25.5 * SR)
|
|
day = join(mix, s, e, 3.0)
|
|
bed = lufs(os.path.join(AUDIO, "waves_loop.wav"))
|
|
to_lufs("wind_meadow_loop", day, bed)
|
|
# the code still plays waves_loop for the ambience, until it moves to the new name
|
|
shutil.copyfile(os.path.join(FINAL, "wind_meadow_loop.wav"), os.path.join(FINAL, "waves_loop.wav"))
|
|
print(" waves_loop.wav copy of wind_meadow_loop")
|
|
|
|
crick = M.lowpass(stereo("farm_night_crickets_0"), 13000)
|
|
breeze = stereo("farm2_wind_0")
|
|
k = min(len(crick), len(breeze))
|
|
crick, breeze = crick[:k], breeze[::-1][:k] # the same wind backwards, so day and night do not swell alike
|
|
night = crick / rms(crick) * M.db(-32) + breeze / rms(breeze) * M.db(-36)
|
|
s, e = int(0.5 * SR), int(25.5 * SR)
|
|
night = join(night, s, e, 3.0)
|
|
to_lufs("night_crickets_loop", night, bed)
|
|
|
|
|
|
def features(x, hop=1024):
|
|
"""Per frame: timbre (48 log bands), harmony (12 pitch classes), and beats (spectral flux)."""
|
|
m = M.mono(x).astype(np.float32)
|
|
f, t, Z = signal.stft(m, SR, nperseg=4096, noverlap=4096 - hop, padded=False, boundary=None)
|
|
p = np.abs(Z) ** 2
|
|
edges = np.geomspace(60, 12000, 49)
|
|
B = np.stack([p[(f >= a) & (f < b)].sum(axis=0) + 1e-9 for a, b in zip(edges[:-1], edges[1:])], axis=1)
|
|
B = np.log(B)
|
|
B -= B.mean(axis=0)
|
|
B /= np.linalg.norm(B, axis=1, keepdims=True) + 1e-9
|
|
use = (f >= 110) & (f <= 2000)
|
|
pc = np.round(12 * np.log2(f[use] / 440)).astype(int) % 12
|
|
held = p[use]
|
|
C = np.stack([np.sqrt(held[pc == k].sum(axis=0)) for k in range(12)], axis=1)
|
|
C /= np.linalg.norm(C, axis=1, keepdims=True) + 1e-9
|
|
flux = np.maximum(0, np.diff(np.log1p(np.abs(Z) * 100), axis=1)).sum(axis=0)
|
|
flux = np.concatenate([[0], flux])
|
|
O = (flux - flux.mean()) / (flux.std() + 1e-9)
|
|
return B.astype(np.float32), C.astype(np.float32), O.astype(np.float32), hop / SR
|
|
|
|
|
|
def find_loop(x, lo=95.0, hi=135.0, around=4.0):
|
|
"""Best (score, start, end, seconds): the two points whose surroundings match in timbre, chord and beat."""
|
|
B, C, O, dt = features(x)
|
|
block = int(3.0 / dt)
|
|
env = np.sqrt(np.convolve((M.mono(x) ** 2)[:: 1024], np.ones(block) / block, "same"))[: len(O)]
|
|
good = np.where(env > np.median(env) * M.db(-4))[0]
|
|
t0, t1 = int(max(good[0], 3 / dt)), int(good[-1] - 3 / dt)
|
|
W = int(around / dt)
|
|
S = int(6.0 / dt) # level of the six seconds after the start and before the end: a pass must not end louder than it began
|
|
power = np.concatenate([[0.0], np.cumsum((M.mono(x) ** 2)[:: 1024][: len(O)], dtype=np.float64)])
|
|
after = dbv(np.sqrt(np.maximum((power[np.minimum(np.arange(len(O)) + S, len(O))] - power[: len(O)]) / S, 0)))
|
|
before = dbv(np.sqrt(np.maximum((power[np.arange(len(O)) + 1] - power[np.maximum(np.arange(len(O)) + 1 - S, 0)]) / S, 0)))
|
|
best = (-9.0, 0, 0)
|
|
for L in range(int(lo / dt), int(hi / dt)):
|
|
if t0 + L >= t1:
|
|
break
|
|
tone = np.sum(B[:-L] * B[L:], axis=1) + np.sum(C[:-L] * C[L:], axis=1)
|
|
c = np.concatenate([[0.0], np.cumsum(tone * 0.5 + 0.5 * O[:-L] * O[L:], dtype=np.float64)])
|
|
score = np.full(len(tone), -9.0) # mean over +-W frames around each point
|
|
score[W: len(tone) - W] = (c[2 * W:] - c[: -2 * W])[: len(tone) - 2 * W] / (2 * W)
|
|
score[:t0] = -9
|
|
score[t1 - L:] = -9
|
|
score[np.abs(before[L:] - after[:-L]) > 2.0] = -9
|
|
i = int(np.argmax(score))
|
|
if score[i] > best[0]:
|
|
best = (float(score[i]), i, i + L)
|
|
return best[0], best[1] * dt, best[2] * dt
|
|
|
|
|
|
def refine(x, s, e, side=4.0, search=0.04):
|
|
"""Slide the end by milliseconds until the beats line up. Returns (end sample, beat likeness, chord likeness)."""
|
|
a, b, k = int(s * SR), int(e * SR), int(side * SR)
|
|
A = M.onset_strength(x[a - k: a + k], hop=128)[0]
|
|
Bo = M.onset_strength(x[b - k: b + k], hop=128)[0]
|
|
r_ = int(search * SR / 128)
|
|
n = min(len(A), len(Bo)) - 2 * r_
|
|
A = A[r_: r_ + n]
|
|
best, shift = -9.0, 0
|
|
for d in range(-r_, r_ + 1):
|
|
c = Bo[r_ + d: r_ + d + n]
|
|
v = float(np.dot(A, c) / (np.linalg.norm(A) * np.linalg.norm(c) + 1e-12))
|
|
if v > best:
|
|
best, shift = v, d
|
|
e_i = b + shift * 128
|
|
# chords over the crossfade itself
|
|
F = features(np.concatenate([x[a: a + int(1.5 * SR)], x[e_i: e_i + int(1.5 * SR)]]))[1]
|
|
half = len(F) // 2
|
|
u, v = F[:half].mean(axis=0), F[half:].mean(axis=0)
|
|
return e_i, best, float(np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v) + 1e-12))
|
|
|
|
|
|
MUSIC = (("music_game_loop", "farm_music_game", "music_game_loop", 0), ("music_game2_loop", "farm_music_game2", "music_game_loop", 0),
|
|
("music_menu_loop", "farm_music_menu", "music_menu_loop", 0), ("music_night_loop", "farm_music_night", "music_game_loop", -3))
|
|
|
|
|
|
def music():
|
|
for out, base, old, offset in MUSIC:
|
|
takes = []
|
|
for name in (base, base + "_b"):
|
|
x = M.raw(name + ".mp3")
|
|
score, s, e = find_loop(x)
|
|
e_i, beat, chord = refine(x, s, e)
|
|
takes.append((beat + chord, name, x, int(s * SR), e_i))
|
|
print(f" {name}: score {score:.3f}, beats {beat:.3f}, chords {chord:.3f}, {s:.2f}s to {e_i / SR:.2f}s = {(e_i - int(s * SR)) / SR:.1f}s")
|
|
_, name, x, s, e = max(takes, key=lambda t: t[0])
|
|
print(f" -> {out} from {name}")
|
|
to_lufs(out, join(x, s, e, 1.5), lufs(os.path.join(AUDIO, old + ".wav")) + offset)
|
|
|
|
|
|
REPLACED = { # new file -> old file to compare with
|
|
"scythe_swing_1": "throw_whoosh", "scythe_swing_2": "throw_whoosh", "scythe_swing_3": "throw_whoosh",
|
|
"shears_snip_1": "snip", "shears_snip_2": "snip", "merger_clunk": "splitter_flip", "press_thump": "compactor_crunch",
|
|
"battery_full": "perk_unlock", "power_low": "error", "tractor_engine_loop": "mower_engine_loop",
|
|
"combine_engine_loop": "mower_engine_loop", "pickup_engine_loop": "mower_engine_loop",
|
|
"robot_mower_loop": "mower_engine_loop", "grass_rustle_loop": "suck_loop", "battery_hum_loop": "machine_hum_loop",
|
|
"wind_meadow_loop": "waves_loop", "night_crickets_loop": "waves_loop", "music_game2_loop": "music_game_loop",
|
|
"music_night_loop": "music_game_loop",
|
|
}
|
|
|
|
|
|
def read(path):
|
|
with wave.open(path) as w:
|
|
info = (w.getframerate(), w.getsampwidth(), w.getnchannels())
|
|
x = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).astype(np.float64) / 32768
|
|
return info, x.reshape(-1, info[2]) if info[2] == 2 else x
|
|
|
|
|
|
def check():
|
|
"""Duration, levels against the old file, and for loops the jump across the join."""
|
|
bad = 0
|
|
print(f"{'file':24}{'ch':>3}{'sec':>8}{'peak':>7}{'rms':>7}{'act':>7}{'old':>7}{'diff':>6} join (step vs typical, level vs usual)")
|
|
for f in sorted(glob.glob(os.path.join(FINAL, "*.wav"))):
|
|
name = os.path.basename(f)[:-4]
|
|
(sr, width, ch), x = read(f)
|
|
m = M.mono(x)
|
|
pk, rms, act = np.abs(x).max(), np.sqrt(np.mean(x ** 2)), active_rms(x)
|
|
ref = REPLACED.get(name, name)
|
|
old = old_level(ref) if os.path.exists(os.path.join(AUDIO, ref + ".wav")) else None
|
|
note = []
|
|
if sr != SR or width != 2:
|
|
note.append("FORMAT")
|
|
if pk > 0.995:
|
|
note.append("CLIPPED")
|
|
if dbv(pk) < -30 or dbv(rms) < -60:
|
|
note.append("SILENT")
|
|
join_txt = ""
|
|
if "_loop" in name:
|
|
step = np.abs(np.diff(x, axis=0)).max(axis=1) if ch == 2 else np.abs(np.diff(x))
|
|
jump = np.abs(x[0] - x[-1]).max() if ch == 2 else abs(x[0] - x[-1])
|
|
typical = np.percentile(step, 99)
|
|
k = int(0.1 * SR)
|
|
blocks = dbv(np.sqrt(np.mean(m[: len(m) // k * k].reshape(-1, k) ** 2, axis=1)))
|
|
lv = blocks[-1] - blocks[0]
|
|
usual = np.percentile(np.abs(np.diff(blocks)), 99) # how much this sound moves between any two 100 ms blocks
|
|
join_txt = f" {jump:.4f} vs {typical:.4f}, {lv:+.1f} vs {usual:.1f}"
|
|
if jump > max(typical, 0.002):
|
|
note.append("JUMP")
|
|
if abs(lv) > max(usual, 1.5):
|
|
note.append("LEVELSTEP")
|
|
bad += len(note)
|
|
old_txt = f"{old:7.1f}{dbv(act) - old:6.1f}" if old is not None else " " * 13
|
|
print(f"{name:24}{ch:3}{len(m) / SR:8.2f}{dbv(pk):7.1f}{dbv(rms):7.1f}{dbv(act):7.1f}{old_txt}{join_txt} {' '.join(note)}")
|
|
print("problems:", bad)
|
|
for name, ref in (("wind_meadow_loop", "waves_loop"), ("night_crickets_loop", "waves_loop"), ("music_game_loop", "music_game_loop"),
|
|
("music_game2_loop", "music_game_loop"), ("music_menu_loop", "music_menu_loop"), ("music_night_loop", "music_game_loop")):
|
|
f = os.path.join(FINAL, name + ".wav")
|
|
if os.path.exists(f):
|
|
print(f"{name:24}{lufs(f):7.1f} LUFS (old {ref}: {lufs(os.path.join(AUDIO, ref + '.wav')):.1f})")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
groups = {"shots": shots, "loops": loops, "ambience": ambience, "music": music, "check": check}
|
|
for g in sys.argv[1:] or list(groups):
|
|
print(f"[{g}]")
|
|
groups[g]()
|