diff --git a/main/xiaozhi-server/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py index 77d740a95..0d5357ce1 100644 --- a/main/xiaozhi-server/core/providers/tts/edge.py +++ b/main/xiaozhi-server/core/providers/tts/edge.py @@ -1,23 +1,78 @@ +import json import os import uuid + import edge_tts -import edge_tts.communicate # 显式 import,下方要给本模块的 WSS_URL 重新赋值 +import edge_tts.communicate from datetime import datetime + +from config.logger import setup_logging from core.providers.tts.base import TTSProviderBase -# 微软 2026-10 起对 legacy 消费者接口返回 403,edge-tts 7.2.8 仍走 -# speech.platform.bing.com 走不通。上游 PR rany2/edge-tts#491 切到 -# api.msedgeservices.com 修好,但 7.2.8 仍是 PyPI 最新版本,临时把 WSS_URL 顶住。 -# TODO(7.2.9): 升 edge-tts ≥ 7.2.9 后删掉这段 monkey patch。 -_NEW_WSS_URL = ( - "wss://api.msedgeservices.com/tts/cognitiveservices/websocket/v1" - f"?Ocp-Apim-Subscription-Key={edge_tts.constants.TRUSTED_CLIENT_TOKEN}" -) -# communicate.py 第 35 行 `from .constants import WSS_URL` 会在 import 时把 -# WSS_URL 复制成本模块局部名,只改 edge_tts.constants.WSS_URL 不会生效。 -# __stream() 走 LEGB 找的是 edge_tts.communicate.WSS_URL,所以这里两个都要改。 -edge_tts.constants.WSS_URL = _NEW_WSS_URL -edge_tts.communicate.WSS_URL = _NEW_WSS_URL +TAG = __name__ +logger = setup_logging() + +# edge_tts 7.3.1 在 ws 返回坏 metadata 帧(非 JSON 或非 utf-8 bytes)时, +# 父类 __parse_metadata 调 json.loads 抛 JSONDecodeError / UnicodeDecodeError; +# stream() 的音频收帧循环被中断,听不到声音。 +# +# 父类 __stream 内部用编译期锁死的 mangled 名 +# `self._Communicate__parse_metadata(data)` 调用,子类覆写根本走不到,所以 +# 必须在父类 Communicate 类上做 monkey-patch:替换 mangled 方法为带兜底的 +# wrapper,让坏帧悄悄丢掉,音频二进制帧继续往下走。连续坏帧超阈值主动 +# raise NoAudioReceived 让 base.py 的 5 次重试接管。 +# +# Communicate 类内 `__parse_metadata` 写法在类外访问必须用 mangled 名 +# `_Communicate__parse_metadata`;直接用 `"__parse_metadata"` 字面访问永远拿不到。 +_METADATA_FALLBACK_COUNT = 5 +_PARSED_METADATA_ATTR = "_Communicate__parse_metadata" + + +def _install_metadata_patch(): + """模块级一次性 patch,import 时执行。 + + 三道闸门: + 1. 探测父类 mangled 方法存在;不存在则 wrapper 不写入(patch 哑火) + 2. wrapper 仅捕获 json.JSONDecodeError + UnicodeDecodeError; + KeyError/UnknownResponse/UnexpectedResponse 等真协议错误冒泡给 base.py 重试 + 3. 连续坏帧超 _METADATA_FALLBACK_COUNT 主动 raise NoAudioReceived + """ + cls = edge_tts.communicate.Communicate + original = cls.__dict__.get(_PARSED_METADATA_ATTR) + if original is None: + logger.bind(tag=TAG).error( + f"edge-tts Communicate.{_PARSED_METADATA_ATTR} 不存在," + "metadata patch 失效,升级 edge_tts 后清掉这段兜底" + ) + return + + def wrapper(self, data): + try: + return original(self, data) + except (json.JSONDecodeError, UnicodeDecodeError) as e: + count = self.state.get("bad_metadata_count", 0) + 1 + self.state["bad_metadata_count"] = count + logger.bind(tag=TAG).warning( + f"edge-tts metadata 帧非 JSON,已忽略(第 {count}/{_METADATA_FALLBACK_COUNT} 次): {e}" + ) + if count > _METADATA_FALLBACK_COUNT: + raise edge_tts.exceptions.NoAudioReceived( + f"edge-tts 连续 {count} 次返回非 JSON metadata 帧" + ) + return { + "type": "metadata_ignored", + "offset": 0, + "duration": 0, + "text": "", + } + + setattr(cls, _PARSED_METADATA_ATTR, wrapper) + logger.bind(tag=TAG).info( + f"edge-tts Communicate.{_PARSED_METADATA_ATTR} patch 安装成功" + ) + + +_install_metadata_patch() class TTSProvider(TTSProviderBase): @@ -44,7 +99,6 @@ class TTSProvider(TTSProviderBase): pitch_rate = config.get("pitch", "0") self.pitch_rate = int(pitch_rate) if pitch_rate else 0 - # 应用百分比调整 self._apply_percentage_params(config) self.edge_rate = f"{self.speech_rate:+}%" @@ -58,32 +112,26 @@ class TTSProvider(TTSProviderBase): ) async def text_to_speak(self, text, output_file): - try: - communicate = edge_tts.Communicate( - text, - voice=self.voice, - rate=self.edge_rate, - volume=self.edge_volume, - pitch=self.edge_pitch, - ) - if output_file: - # 确保目录存在并创建空文件 - os.makedirs(os.path.dirname(output_file), exist_ok=True) - with open(output_file, "wb") as f: - pass + communicate = edge_tts.communicate.Communicate( + text, + voice=self.voice, + rate=self.edge_rate, + volume=self.edge_volume, + pitch=self.edge_pitch, + ) + if output_file: + os.makedirs(os.path.dirname(output_file), exist_ok=True) + with open(output_file, "wb") as f: + pass - # 流式写入音频数据 - with open(output_file, "ab") as f: # 改为追加模式避免覆盖 - async for chunk in communicate.stream(): - if chunk["type"] == "audio": # 只处理音频数据块 - f.write(chunk["data"]) - else: - # 返回音频二进制数据 - audio_bytes = b"" + with open(output_file, "ab") as f: async for chunk in communicate.stream(): - if chunk["type"] == "audio": - audio_bytes += chunk["data"] - return audio_bytes - except Exception as e: - error_msg = f"Edge TTS请求失败: {e}" - raise Exception(error_msg) # 抛出异常,让调用方捕获 \ No newline at end of file + if chunk.get("type") == "audio": + f.write(chunk["data"]) + else: + audio_bytes = b"" + async for chunk in communicate.stream(): + if chunk.get("type") == "audio": + audio_bytes += chunk["data"] + return audio_bytes + return None diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 9b056c666..81547ac05 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -4,6 +4,7 @@ import json import copy import wave import socket +import sys import asyncio import requests import subprocess @@ -12,8 +13,25 @@ import opuslib_next from io import BytesIO from core.utils import p3 from pydub import AudioSegment +import pydub.utils as _pdu from typing import Callable, Any +# pydub 调 ffprobe / ffmpeg 是按 PATH 找第一个,但 PATH 里常被 IDE(Trae CN +# 等)注入的精简版占位(不认 mp3 demuxer、没 cache 协议),导致解析 mp3 +# 字节流时 ffprobe 报 "Protocol not found"、stdout 空,pydub json.loads("") +# 抛 JSONDecodeError,错误冒到 base.py 5-retry except 报"语音生成失败"。 +# 这里把 pydub 的 prober / encoder 显式绑到当前 Python 解释器同目录的 +# ffprobe / ffmpeg(conda env / 系统 venv 配套的完整版),不依赖 PATH 顺序; +# 探测不到时优雅降级到 pydub 默认行为。 +_bin_dir = os.path.dirname(sys.executable) +_conda_ffprobe = os.path.join(_bin_dir, "ffprobe") +_conda_ffmpeg = os.path.join(_bin_dir, "ffmpeg") +if os.path.isfile(_conda_ffprobe): + _pdu.get_prober_name = lambda: _conda_ffprobe + setattr(AudioSegment, "converter", _conda_ffmpeg) +if os.path.isfile(_conda_ffmpeg): + _pdu.get_encoder_name = lambda: _conda_ffmpeg + TAG = __name__ diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index 055bf30fc..34dc25e52 100644 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -13,7 +13,7 @@ pydub==0.25.1 funasr==1.2.7 openai==2.8.1 google-generativeai==0.8.5 -edge_tts==7.2.8 +edge_tts==7.3.1 httpx==0.28.1 aiohttp==3.13.2 aiohttp_cors==0.8.1