cosmo/scripts/gen_countdown_voice.py

61 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""生成火箭点火启动倒数(10→1 → Lift off)的英文男声语音,合成成一段约 10 秒的音频。
依赖系统自带的 `say`(macOS)与 `ffmpeg`。每个数字被放在倒数轴上的对应时刻:
"10" 在 t=0,"9" 在 t=1s … "1" 在 t=9s,"Lift off" 在 t=10s(即起飞那一刻)。
物理侧 COUNTDOWN_SECONDS=10,正好对上。
用法:python3 scripts/gen_countdown_voice.py
输出:backend/upload/assets/countdown.m4a(随 git 分发)。
"""
import subprocess
import sys
import tempfile
from pathlib import Path
ASSETS = Path(__file__).resolve().parent.parent / "backend" / "upload" / "assets"
OUT = ASSETS / "countdown.m4a"
VOICE = "Daniel" # macOS 内置的英文男声
COUNTDOWN_SECONDS = 10
def run(cmd):
subprocess.run(cmd, check=True, capture_output=True)
def main() -> None:
ASSETS.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
# 每句独立合成成 PCM(aiff 是 AIFF-C 压缩,交给 ffmpeg 统一转码更稳)
lines = [str(n) for n in range(COUNTDOWN_SECONDS, 0, -1)] + ["Lift off"]
clips = []
for i, text in enumerate(lines):
aiff = tmp / f"{i:02d}.aiff"
run(["say", "-v", VOICE, "-o", str(aiff), text])
clips.append((i, aiff))
# 用 adelay 把每句推到它该说的时刻(第 i 句在 i 秒处),再 amix 叠在一起。
inputs = []
filters = []
for i, aiff in clips:
delay = i * 1000
inputs += ["-i", str(aiff)]
filters.append(f"[{i}:a]aresample=44100,adelay={delay}|{delay},apad[a{i}]")
# normalize=0:各路互不重叠,直接相加即可,别被 amix 按路数摊薄
mix = "".join(f"[a{i}]" for i, _ in clips) + f"amix=inputs={len(clips)}:duration=longest:normalize=0[aout]"
filters.append(mix)
# 直接 aac 编码成 m4a(浏览器支持一致,体积也小)
run(["ffmpeg", "-y", *inputs, "-filter_complex", ";".join(filters),
"-map", "[aout]",
"-t", str(COUNTDOWN_SECONDS + 2), "-c:a", "aac", "-b:a", "128k", str(OUT)])
print(f"{OUT.name}: {OUT.stat().st_size // 1024} KB")
if __name__ == "__main__":
try:
main()
except subprocess.CalledProcessError as err:
sys.exit(f"audio 生成失败:\n{err.stderr.decode(errors='replace')}")