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