Files
ComfyGen/level.py

96 lines
3.2 KiB
Python
Raw Permalink Normal View History

"""Set a generated clip to a known peak, so 'too loud' is a number.
The audio counterpart of trim.py. Stable Audio renders whatever level the prompt
suggests to it, and the prompt is about the *sound* rather than about the level:
asking for "a big bright water impact" gave a clip pinned at 0 dB with a hard
transient, and asking for the same moment gently gave three rolls in a row at
around -35 dB mean, quieter than the click on a menu button. Neither is a thing
to fix by re-rolling, because neither is what the prompt is for.
So the prompt decides what it sounds like and this decides how loud it is. One
gain applied to the whole clip - no compression, no limiting, nothing that
changes the shape of it, because the shape is what came out of the model and is
the part worth keeping.
py level.py aq_sfx_intro_hit # newest roll, to the default peak
py level.py aq_sfx_intro_hit -6 # to -6 dB instead
py level.py assets/sounds/aq_sfx_won.mp3 -3
Writes `<name>_levelled.mp3` beside the source. Copy into the game by hand -
nothing here touches assets/.
"""
import glob
import os
import re
import subprocess
import sys
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
OUT = os.path.join(config.OUTPUT_DIR, getattr(config, "AUDIO_SUBDIR", "audio"))
# Where a one-off sound sits. Not 0: a clip that touches the ceiling has nothing
# left for the mixer, and everything in this game can play over something else.
DEFAULT_PEAK = -3.0
def measured(path):
"""The clip's peak and mean, in dB, as ffmpeg reports them."""
run = subprocess.run(
["ffmpeg", "-hide_banner", "-i", path, "-af", "volumedetect", "-f", "null", "-"],
capture_output=True, text=True, check=False)
def find(what):
hit = re.search(rf"{what}:\s*(-?[\d.]+) dB", run.stderr)
return float(hit.group(1)) if hit else None
return find("max_volume"), find("mean_volume")
def level(path, peak):
top, mean = measured(path)
if top is None:
print(f" {os.path.basename(path)}: could not be measured, skipped")
return
gain = peak - top
stem = re.sub(r"_\d+$", "", os.path.splitext(os.path.basename(path))[0])
dest = os.path.join(os.path.dirname(path), f"{stem}_levelled.mp3")
subprocess.run(
["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", path,
"-af", f"volume={gain:.2f}dB", "-codec:a", "libmp3lame", "-q:a", "2", dest],
check=True)
after, afterMean = measured(dest)
print(f" {stem:24s} peak {top:6.1f} -> {after:6.1f} dB "
f"mean {mean:6.1f} -> {afterMean:6.1f} dB ({gain:+.1f} dB)")
def main():
if len(sys.argv) < 2:
print(__doc__)
return 1
name = sys.argv[1]
peak = float(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_PEAK
if os.path.isfile(name):
level(name, peak)
return 0
# A name rather than a path: the newest roll of it in output/audio.
found = sorted(glob.glob(os.path.join(OUT, f"{name}*.mp3")))
found = [f for f in found if not f.endswith("_levelled.mp3")]
if not found:
print(f"no clip found for {name} in {OUT}")
return 1
level(found[-1], peak)
return 0
if __name__ == "__main__":
raise SystemExit(main())