120 lines
5.3 KiB
Python
120 lines
5.3 KiB
Python
"""macOS 系统语音适配器:把真实 TTS 能力接入统一配音流水线。
|
||
|
||
``say`` 是 macOS 自带命令,适合本地开发与离线成片。适配器统一输出单声道
|
||
PCM WAV,并可对音色追加滤镜,例如铁血战士的外星语效果。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import shutil
|
||
import subprocess
|
||
import tempfile
|
||
from pathlib import Path
|
||
|
||
from app.config import settings
|
||
from app.providers.base import (FatalProviderError, VoiceGenRequest, VoiceGenResult,
|
||
VoiceProviderAdapter)
|
||
from app.services import ffmpeg as ff
|
||
|
||
|
||
# 低频化 + 金属共振 + 颗粒噪声;保持原始语速的同时明显降低音高。
|
||
ALIEN_AUDIO_FILTER = (
|
||
"asetrate=22050*0.62,aresample=22050,atempo=1.6129,"
|
||
"flanger=delay=4:depth=3:regen=25:width=60:speed=0.4,"
|
||
"aecho=0.8:0.7:40|90:0.35|0.2,"
|
||
"acrusher=bits=8:mode=log:aa=1,lowpass=f=4800,tremolo=f=7:d=0.25"
|
||
)
|
||
|
||
|
||
class MacOSSayVoiceProvider(VoiceProviderAdapter):
|
||
"""使用 macOS ``say`` 合成可听的真实语音。
|
||
|
||
声线通过 ``provider_voice_id`` 指定,例如 ``Tingting``、``Meijia``、
|
||
``Sinji`` 或 ``Fred``。``request.params.effect = "alien"`` 会启用外星语
|
||
滤镜链。模型配置中的 ``voice`` 和 ``effect`` 可作为默认值。
|
||
"""
|
||
|
||
_name = "macos_say"
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return self._name
|
||
|
||
def is_available(self, config: dict | None = None) -> bool:
|
||
return bool(shutil.which("say")) and ff.available()
|
||
|
||
def synthesize(self, request: VoiceGenRequest, config: dict | None = None) -> VoiceGenResult:
|
||
config = config or {}
|
||
say_bin = shutil.which("say")
|
||
if not say_bin:
|
||
raise FatalProviderError("当前系统没有 macOS say 命令,无法使用 macos_say 配音",
|
||
code="say_unavailable")
|
||
if not ff.available():
|
||
raise FatalProviderError("本机缺少 ffmpeg/ffprobe,无法转换 say 音频",
|
||
code="ffmpeg_unavailable")
|
||
|
||
text = (request.text or "").strip()
|
||
if not text:
|
||
raise FatalProviderError("配音文本为空", code="empty_text")
|
||
|
||
voice = (request.provider_voice_id or config.get("voice") or "Tingting").strip()
|
||
if not voice:
|
||
raise FatalProviderError("未配置 macOS 系统声线 ID", code="missing_voice")
|
||
speed = max(0.5, min(float(request.speed or 1.0), 2.0))
|
||
rate = max(80, min(420, int(round(180 * speed))))
|
||
|
||
out = Path(request.output_path or settings.media_root / "macos_say" / "voice.wav")
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
with tempfile.TemporaryDirectory(prefix="nex-say-") as tmp:
|
||
raw = Path(tmp) / "speech.aiff"
|
||
say_cmd = [say_bin, "-v", voice, "-r", str(rate), "-o", str(raw), "--", text]
|
||
try:
|
||
proc = subprocess.run(say_cmd, capture_output=True, text=True, timeout=120)
|
||
except subprocess.TimeoutExpired as exc:
|
||
raise FatalProviderError("macOS say 合成超时", code="say_timeout") from exc
|
||
if proc.returncode != 0:
|
||
detail = (proc.stderr or proc.stdout or "未知错误").strip()
|
||
raise FatalProviderError(
|
||
f"macOS say 合成失败(声线 {voice}):{detail}",
|
||
code="say_failed", detail={"voice": voice, "stderr": detail})
|
||
if not raw.exists() or raw.stat().st_size < 512:
|
||
raise FatalProviderError(
|
||
f"声线「{voice}」没有生成有效音频,可能尚未下载到本机",
|
||
code="say_empty_output", detail={"voice": voice})
|
||
|
||
filters = []
|
||
effect = str(request.params.get("effect") or config.get("effect") or "").lower()
|
||
pitch = max(0.5, min(float(request.pitch or 1.0), 2.0))
|
||
if effect == "alien":
|
||
filters.append(ALIEN_AUDIO_FILTER)
|
||
elif abs(pitch - 1.0) > 0.01:
|
||
sample_rate = max(8000, min(int(request.sample_rate or 24000), 48000))
|
||
filters.extend([
|
||
f"asetrate={sample_rate}*{pitch:.4f}",
|
||
f"aresample={sample_rate}",
|
||
f"atempo={1.0 / pitch:.4f}",
|
||
])
|
||
|
||
cmd = [ff.FFMPEG, "-v", "error", "-y", "-i", str(raw), "-vn"]
|
||
if filters:
|
||
cmd += ["-af", ",".join(filters)]
|
||
cmd += ["-ar", str(max(8000, min(int(request.sample_rate or 24000), 48000))),
|
||
"-ac", "1", "-c:a", "pcm_s16le", str(out)]
|
||
ff.run(cmd, timeout=180)
|
||
|
||
probed = ff.probe(out)
|
||
duration = float(probed.duration or 0.0)
|
||
if not out.exists() or out.stat().st_size < 512 or duration < 0.3:
|
||
raise FatalProviderError(
|
||
f"声线「{voice}」输出的音频过短({duration:.3f}s),请换用已下载的系统语音",
|
||
code="say_invalid_audio", detail={"voice": voice, "duration": duration})
|
||
|
||
return VoiceGenResult(
|
||
file_path=str(out),
|
||
duration_ms=int(round(duration * 1000)),
|
||
provider_job_id=f"macos-say-{abs(hash((voice, text, effect))) % 10**10}",
|
||
cost=0.0,
|
||
metadata={"provider": "macos_say", "voice": voice, "effect": effect,
|
||
"rate": rate, "duration": duration, "real": True},
|
||
)
|