wobblyhead hg > minor_monsters
comparison tools/cut_sounds.py @ 4:2d46729a022e
sound processing and in-game sounds
| author | ark |
|---|---|
| date | 2026-10-18 20:58 +0200 |
| parents | |
| children | 85d23328a215 |
comparison
equal
deleted
inserted
replaced
| 3:cc0c32e71090 | 4:2d46729a022e |
|---|---|
| 1 """ | |
| 2 cut the voice recordings in art/sound_sources/ into game sounds in art/sounds/. | |
| 3 | |
| 4 python3 tools/cut_sounds.py [NAME ...] | |
| 5 | |
| 6 without names, every recording is processed. a recording is named after its | |
| 7 game event (doc/sound.md). one with several variants, listed in VARIANTS, is | |
| 8 split into that many sounds, written as NAME_1.mp3, NAME_2.mp3 and so on; any | |
| 9 other recording becomes one sound, NAME.mp3. | |
| 10 | |
| 11 each sound is filtered against low rumble, trimmed to the voice with a short | |
| 12 margin, faded in and out, brought to the same peak level and written as mono | |
| 13 mp3. a recording is split at its longest pauses: as many as it takes to give | |
| 14 the listed number of variants. pauses inside one sound are left alone. | |
| 15 | |
| 16 requires ffmpeg with libmp3lame, which the build does not need: the build | |
| 17 reads art/sounds/ only. run this script by hand after a recording changes. | |
| 18 """ | |
| 19 | |
| 20 import math | |
| 21 import subprocess | |
| 22 import sys | |
| 23 from array import array | |
| 24 from pathlib import Path | |
| 25 | |
| 26 ART = Path(__file__).resolve().parent.parent / "art" | |
| 27 SOURCES = ART / "sound_sources" | |
| 28 SOUNDS = ART / "sounds" | |
| 29 | |
| 30 # number of variants in a recording (doc/art.md) | |
| 31 VARIANTS = { | |
| 32 "t0_attack": 4, | |
| 33 "t1_shot": 6, | |
| 34 "t2_shot": 4, | |
| 35 "t3_shot": 7, | |
| 36 "monster_enter": 3, | |
| 37 "monster_die": 4, | |
| 38 } | |
| 39 | |
| 40 RATE = 44100 | |
| 41 BITRATE = "64k" | |
| 42 # remove rumble below this frequency, Hz | |
| 43 HIGHPASS = 80 | |
| 44 # level analysis in frames of this length, s | |
| 45 FRAME = 0.01 | |
| 46 # a frame is voice when its level is within this many dB of the loudest frame | |
| 47 THRESHOLD_DB = 35 | |
| 48 # shorter bits of voice are clicks and dropped, s | |
| 49 MIN_SOUND = 0.03 | |
| 50 # margin kept before and after the voice, s | |
| 51 MARGIN_IN = 0.02 | |
| 52 MARGIN_OUT = 0.05 | |
| 53 # fade lengths at the cut ends, s | |
| 54 FADE_IN = 0.005 | |
| 55 FADE_OUT = 0.03 | |
| 56 # peak level of every sound, dB below full scale | |
| 57 PEAK_DB = -1.0 | |
| 58 # warn when the shortest split pause is less than this times the longest | |
| 59 # pause kept inside a sound | |
| 60 SPLIT_MARGIN = 1.5 | |
| 61 | |
| 62 | |
| 63 def decode(path): | |
| 64 """decode a recording to mono 16 bit samples at RATE, rumble filtered.""" | |
| 65 out = subprocess.run( | |
| 66 ["ffmpeg", "-v", "error", "-i", str(path), "-af", f"highpass=f={HIGHPASS}", | |
| 67 "-ac", "1", "-ar", str(RATE), "-f", "s16le", "-"], | |
| 68 check=True, capture_output=True).stdout | |
| 69 samples = array("h") | |
| 70 samples.frombytes(out) | |
| 71 if sys.byteorder == "big": | |
| 72 samples.byteswap() | |
| 73 return samples | |
| 74 | |
| 75 | |
| 76 def encode(samples, path): | |
| 77 data = array("h", samples) | |
| 78 if sys.byteorder == "big": | |
| 79 data.byteswap() | |
| 80 # bitexact keeps the encoder version out of the file, so the output | |
| 81 # changes only when the sound does | |
| 82 subprocess.run( | |
| 83 ["ffmpeg", "-v", "error", "-y", "-f", "s16le", "-ar", str(RATE), "-ac", "1", | |
| 84 "-i", "-", "-c:a", "libmp3lame", "-b:a", BITRATE, "-map_metadata", "-1", | |
| 85 "-flags", "+bitexact", "-fflags", "+bitexact", str(path)], | |
| 86 input=data.tobytes(), check=True) | |
| 87 | |
| 88 | |
| 89 def voice(samples): | |
| 90 """ | |
| 91 return the stretches of voice as (start, end) in samples, in order. | |
| 92 clicks shorter than MIN_SOUND are dropped. | |
| 93 """ | |
| 94 n = int(FRAME * RATE) | |
| 95 levels = [] | |
| 96 for i in range(0, len(samples) - n + 1, n): | |
| 97 frame = samples[i:i + n] | |
| 98 rms = math.sqrt(sum(v * v for v in frame) / n) | |
| 99 levels.append(20 * math.log10(rms) if rms > 0 else -200.0) | |
| 100 limit = max(levels) - THRESHOLD_DB | |
| 101 runs, start = [], None | |
| 102 for i, lv in enumerate(levels + [-200.0]): | |
| 103 if lv >= limit and start is None: | |
| 104 start = i | |
| 105 elif lv < limit and start is not None: | |
| 106 runs.append((start * n, i * n)) | |
| 107 start = None | |
| 108 return [r for r in runs if r[1] - r[0] >= MIN_SOUND * RATE] | |
| 109 | |
| 110 | |
| 111 def split(runs, count, name): | |
| 112 """group the voice stretches into count sounds at the longest pauses.""" | |
| 113 gaps = sorted(range(len(runs) - 1), key=lambda i: runs[i + 1][0] - runs[i][1], reverse=True) | |
| 114 if len(gaps) < count - 1: | |
| 115 sys.exit(f"{name}: found {len(runs)} stretch(es) of voice, need {count} variants") | |
| 116 cuts = sorted(gaps[:count - 1]) | |
| 117 length = [(runs[i + 1][0] - runs[i][1]) / RATE for i in gaps] | |
| 118 if count > 1 and len(length) >= count and length[count - 2] < SPLIT_MARGIN * length[count - 1]: | |
| 119 print(f" warning: {name}: split pause {length[count - 2]:.2f} s is close to" | |
| 120 f" a pause kept inside a sound, {length[count - 1]:.2f} s") | |
| 121 out, first = [], 0 | |
| 122 for c in cuts + [len(runs) - 1]: | |
| 123 out.append((runs[first][0], runs[c][1])) | |
| 124 first = c + 1 | |
| 125 return out | |
| 126 | |
| 127 | |
| 128 def shape(samples, start, end): | |
| 129 """cut one sound with margins, fade its ends and set its peak level.""" | |
| 130 a = max(0, start - int(MARGIN_IN * RATE)) | |
| 131 b = min(len(samples), end + int(MARGIN_OUT * RATE)) | |
| 132 part = samples[a:b] | |
| 133 peak = max(abs(v) for v in part) | |
| 134 gain = 32767 * 10 ** (PEAK_DB / 20) / peak | |
| 135 fin, fout = int(FADE_IN * RATE), int(FADE_OUT * RATE) | |
| 136 n = len(part) | |
| 137 out = array("h", bytes(2 * n)) | |
| 138 for i, v in enumerate(part): | |
| 139 g = gain | |
| 140 if i < fin: | |
| 141 g *= i / fin | |
| 142 if n - i <= fout: | |
| 143 g *= (n - 1 - i) / fout | |
| 144 out[i] = max(-32768, min(32767, round(v * g))) | |
| 145 return out | |
| 146 | |
| 147 | |
| 148 def process(path): | |
| 149 name = path.stem | |
| 150 count = VARIANTS.get(name, 1) | |
| 151 samples = decode(path) | |
| 152 runs = voice(samples) | |
| 153 if not runs: | |
| 154 sys.exit(f"{name}: no voice found") | |
| 155 sounds = split(runs, count, name) if count > 1 else [(runs[0][0], runs[-1][1])] | |
| 156 for old in list(SOUNDS.glob(f"{name}.mp3")) + list(SOUNDS.glob(f"{name}_[0-9]*.mp3")): | |
| 157 old.unlink() | |
| 158 for i, (start, end) in enumerate(sounds, start=1): | |
| 159 dst = SOUNDS / (f"{name}_{i}.mp3" if count > 1 else f"{name}.mp3") | |
| 160 encode(shape(samples, start, end), dst) | |
| 161 print(f" {dst.name}: {start / RATE:.2f}-{end / RATE:.2f} s of the recording," | |
| 162 f" {(end - start) / RATE:.2f} s") | |
| 163 | |
| 164 | |
| 165 def main(names): | |
| 166 # any format ffmpeg reads | |
| 167 paths = sorted(p for p in SOURCES.iterdir() if p.is_file() and not p.name.startswith(".")) | |
| 168 if names: | |
| 169 paths = [p for p in paths if p.stem in names] | |
| 170 missing = set(names) - {p.stem for p in paths} | |
| 171 if missing: | |
| 172 sys.exit("no recording for: " + ", ".join(sorted(missing))) | |
| 173 SOUNDS.mkdir(exist_ok=True) | |
| 174 for p in paths: | |
| 175 print(p.name) | |
| 176 process(p) | |
| 177 | |
| 178 | |
| 179 if __name__ == "__main__": | |
| 180 main(sys.argv[1:]) |
