- MCP Streamable HTTP (:8765 HTTP / :8766 HTTPS 自签) - 工具:speak / play_url / play_file / download / stop / set_volume / list_voices / list_music / player_status / status - 音量:上限 100,默认 30,夜间 22:00-08:30 静默压到 60 - CORS + Origin 白名单(局域网网段 + Android WebView 虚拟域) - audio.py:PipeWire 蓝牙输出、JBL 绝对音量校验、播放状态/进度/设备信息 - tts.py:edge-tts 合成 + 缓存 - bt-play.sh:命令行播放工具
79 lines
2.9 KiB
Python
79 lines
2.9 KiB
Python
"""
|
|
TTS 层:edge-tts 合成 + 本地缓存(相同文本+音色不重复请求)。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import hashlib
|
|
import logging
|
|
import time
|
|
from pathlib import Path
|
|
|
|
log = logging.getLogger("ai-speaker.tts")
|
|
|
|
DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural"
|
|
CACHE_DIR = Path("/vol1/1000/Programs/ai-speaker/cache")
|
|
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
# 常用中文音色,供 list_voices 返回
|
|
VOICES = {
|
|
"zh-CN-XiaoxiaoNeural": "晓晓(女,标准,默认)",
|
|
"zh-CN-XiaoyiNeural": "晓伊(女,柔和)",
|
|
"zh-CN-YunxiNeural": "云希(男,年轻)",
|
|
"zh-CN-YunjianNeural": "云健(男,浑厚,适合播报)",
|
|
"zh-CN-YunyangNeural": "云扬(男,新闻播音)",
|
|
"zh-CN-YunxiaNeural": "云夏(男,童声/活泼)",
|
|
"zh-CN-liaoning-XiaobeiNeural": "晓北(女,东北口音)",
|
|
"zh-CN-shaanxi-XiaoniNeural": "晓妮(女,陕西口音)",
|
|
}
|
|
|
|
|
|
def _cache_path(text: str, voice: str, rate: str, volume: str) -> Path:
|
|
key = hashlib.sha256(f"{voice}|{rate}|{volume}|{text}".encode()).hexdigest()[:24]
|
|
return CACHE_DIR / f"{key}.mp3"
|
|
|
|
|
|
async def _synth(text: str, voice: str, rate: str, volume: str, out: Path) -> None:
|
|
import edge_tts
|
|
kw = {"rate": rate, "volume": volume}
|
|
if rate == "+0%":
|
|
kw.pop("rate")
|
|
if volume == "+0%":
|
|
kw.pop("volume")
|
|
communicate = edge_tts.Communicate(text, voice, **kw)
|
|
await communicate.save(str(out))
|
|
|
|
|
|
def synthesize(text: str, voice: str = DEFAULT_VOICE, rate: str = "+0%", volume: str = "+0%") -> dict:
|
|
"""
|
|
合成语音到缓存文件。返回 {"ok","path","cached","seconds"}。
|
|
失败返回 {"ok": False, "error"}。
|
|
"""
|
|
text = (text or "").strip()
|
|
if not text:
|
|
return {"ok": False, "error": "文本为空"}
|
|
if len(text) > 1500:
|
|
return {"ok": False, "error": f"文本过长({len(text)} 字),上限 1500 字"}
|
|
if voice not in VOICES:
|
|
return {"ok": False, "error": f"不支持的音色 {voice},可选: {', '.join(VOICES)}"}
|
|
out = _cache_path(text, voice, rate, volume)
|
|
if out.exists() and out.stat().st_size > 0:
|
|
return {"ok": True, "path": str(out), "cached": True, "seconds": 0.0}
|
|
t0 = time.time()
|
|
tmp = out.with_suffix(".tmp.mp3")
|
|
try:
|
|
asyncio.run(asyncio.wait_for(_synth(text, voice, rate, volume, tmp), timeout=30))
|
|
if not tmp.exists() or tmp.stat().st_size == 0:
|
|
raise RuntimeError("合成结果为空")
|
|
tmp.rename(out)
|
|
except Exception as e:
|
|
tmp.unlink(missing_ok=True)
|
|
log.exception("TTS 合成失败")
|
|
return {"ok": False, "error": f"{type(e).__name__}: {str(e)[:150]}"}
|
|
return {"ok": True, "path": str(out), "cached": False, "seconds": round(time.time() - t0, 2)}
|
|
|
|
|
|
def cache_stats() -> dict:
|
|
files = list(CACHE_DIR.glob("*.mp3"))
|
|
return {"count": len(files), "bytes": sum(f.stat().st_size for f in files), "dir": str(CACHE_DIR)}
|