mx / dengtaishan-src /tools /gen_voice.py
Ethscriptions's picture
登泰山记:旁白脚本、93 句旁白音频、字体子集
1b1f125 verified
Raw History Blame Contribute Delete
2.07 kB
# 旁白生成:读取 script.json,逐句调用 edge-tts 生成 mp3,并写出时长清单
import asyncio, json, os, sys, re
import edge_tts
from mutagen.mp3 import MP3
ROOT = sys.argv[1] if len(sys.argv) > 1 else "/workspaces/frontend"
VOICE = "zh-CN-YunyangNeural"
# 生僻字/多音字 → 同音字(仅用于朗读,不影响字幕)
SUBS = [
("砌石为磴", "砌石维邓"), ("磴几不可登", "邓机不可登"),
("姚鼐", "姚耐"), ("汶水", "问水"), ("入汶", "入问"), ("阳汶西", "阳问西"),
("济水", "挤水"), ("入济", "入挤"), ("阴济东", "阴挤东"),
("樗蒱", "出蒲"), ("“樗”", "“出”"), ("“蒱”", "“蒲”"), ("徂徕", "粗来"),
("若偻", "若吕"), ("“偻”", "“吕”"), ("罅", "下"), ("圜", "圆"),
("子颍", "子影"), ("“磴”", "“邓”"), ("日观", "日关"), ("绛皓", "匠浩"), ("长清", "常清"),
]
def spoken(t):
for a, b in SUBS: t = t.replace(a, b)
return t.replace("“", "").replace("”", "")
async def one(sem, line, out):
async with sem:
rate = "-14%" if line["k"] == "q" else "-3%"
pitch = "-4Hz" if line["k"] == "q" else "+0Hz"
path = os.path.join(out, line["id"] + ".mp3")
for attempt in range(4):
try:
c = edge_tts.Communicate(spoken(line["t"]), VOICE, rate=rate, pitch=pitch)
await c.save(path)
break
except Exception as e:
print("retry", line["id"], e); await asyncio.sleep(2)
return line["id"], round(MP3(path).info.length, 3)
async def main():
script = json.load(open(os.path.join(ROOT, "src/video/script.json"), encoding="utf-8"))
out = os.path.join(ROOT, "public/voice"); os.makedirs(out, exist_ok=True)
sem = asyncio.Semaphore(5)
lines = [l for s in script for l in s["lines"]]
res = await asyncio.gather(*[one(sem, l, out) for l in lines])
man = {k: v for k, v in res}
json.dump(man, open(os.path.join(ROOT, "src/video/voice.json"), "w"), ensure_ascii=False, indent=0)
print(len(man), "lines, total", round(sum(man.values()), 1), "s")
asyncio.run(main())