feat: tts fix

This commit is contained in:
Harold 2025-11-10 16:05:19 +08:00
parent cd8356cf70
commit 0b03e9a3f0
5 changed files with 20 additions and 21 deletions

View file

@ -44,7 +44,7 @@ class TTSProvider(TTSProviderBase):
# 标记为单流式接口 # 标记为单流式接口
self.interface_type = InterfaceType.SINGLE_STREAM self.interface_type = InterfaceType.SINGLE_STREAM
# 设置音频文件类型为 WAV # 设置音频文件类型为 PCM
self.audio_file_type = "pcm" self.audio_file_type = "pcm"
# 获取 API Key # 获取 API Key
@ -119,14 +119,14 @@ class TTSProvider(TTSProviderBase):
async def text_to_speak(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]: async def text_to_speak(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]:
""" """
将文本转换为 WAV 格式音频(完整音频,非流式) 将文本转换为 PCM 格式音频(完整音频,非流式)
Args: Args:
text: 要合成的文本 text: 要合成的文本
output_file: 输出文件路径(未使用,保留兼容性) output_file: 输出文件路径(未使用,保留兼容性)
Returns: Returns:
WAV 格式的完整音频字节数据 PCM 格式的完整音频字节数据
""" """
try: try:
ws = self._get_ws_client() ws = self._get_ws_client()

View file

@ -51,10 +51,7 @@ class TTSProvider(TTSProviderBase):
for chunk in audio_stream: for chunk in audio_stream:
f.write(chunk) f.write(chunk)
else: else:
audio_bytes = b"" return b''.join(audio_stream)
for chunk in audio_stream:
audio_bytes += chunk["data"]
return audio_bytes
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Deepgram TTS failed: {e}", exc_info=True) logger.bind(tag=TAG).error(f"Deepgram TTS failed: {e}", exc_info=True)

View file

@ -52,7 +52,7 @@ class TTSProvider(TTSProviderBase):
# 标记为单流式接口 # 标记为单流式接口
self.interface_type = InterfaceType.SINGLE_STREAM self.interface_type = InterfaceType.SINGLE_STREAM
# 设置音频文件类型为 MP3 # 设置音频文件类型为 PCM
self.audio_file_type = "pcm" self.audio_file_type = "pcm"
# 获取 API Key # 获取 API Key
@ -95,24 +95,23 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).info( logger.bind(tag=TAG).info(
f"ElevenLabs SDK initialized: model={self.model}, " f"ElevenLabs SDK initialized: model={self.model}, "
f"voice_id={self.voice_id[:8]}..., " f"voice_id={self.voice_id[:8]}..., "
f"format=mp3_44100" f"format={self.output_format}"
) )
async def text_to_speak(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]: async def text_to_speak(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]:
""" """
将文本转换为 MP3 格式音频(完整音频,非流式) 将文本转换为 PCM 格式音频(完整音频,非流式)
Args: Args:
text: 要合成的文本 text: 要合成的文本
output_file: 输出文件路径(未使用,保留兼容性) output_file: 输出文件路径(未使用,保留兼容性)
Returns: Returns:
MP3 格式的完整音频字节数据 PCM 格式的完整音频字节数据
""" """
try: try:
# 使用 SDK 的 convert 方法生成完整音频(返回 generator) # 使用 SDK 的 convert 方法生成完整音频(返回 generator)
# 强制使用 mp3_44100 格式(忽略配置中的 output_format) # 使用配置的 output_format(如 pcm_16000)
# 因为 base.py 需要完整的音频文件格式(MP3/WAV),而不是原始 PCM
audio_stream = self.client.text_to_speech.convert( audio_stream = self.client.text_to_speech.convert(
voice_id=self.voice_id, voice_id=self.voice_id,
text=text, text=text,
@ -127,9 +126,7 @@ class TTSProvider(TTSProviderBase):
for chunk in audio_stream: for chunk in audio_stream:
f.write(chunk) f.write(chunk)
else: else:
audio_bytes = b"" audio_bytes = b''.join(chunk for chunk in audio_stream if chunk)
for chunk in audio_stream:
audio_bytes += chunk["data"]
return audio_bytes return audio_bytes
except Exception as e: except Exception as e:

View file

@ -92,6 +92,7 @@ class TTSProvider(TTSProviderBase):
config.get('ref_text')if config.get('ref_text') else config.get("reference_text") config.get('ref_text')if config.get('ref_text') else config.get("reference_text")
) )
self.format = config.get("response_format", "pcm") self.format = config.get("response_format", "pcm")
self.sample_rate = config.get("sample_rate", 16000)
self.audio_file_type = config.get("response_format", "pcm") self.audio_file_type = config.get("response_format", "pcm")
self.api_key = config.get("api_key", "YOUR_API_KEY") self.api_key = config.get("api_key", "YOUR_API_KEY")
if self.api_key is None: if self.api_key is None:

View file

@ -315,19 +315,23 @@ def audio_to_data(audio_file_path: str, is_opus: bool = True) -> list[bytes]:
def audio_bytes_to_data_stream(audio_bytes, file_type, is_opus, callback: Callable[[Any], Any]) -> None: def audio_bytes_to_data_stream(audio_bytes, file_type, is_opus, callback: Callable[[Any], Any]) -> None:
""" """
直接用音频二进制数据转为opus/pcm数据,支持wav、mp3、p3 transfer audio bytes to opus/pcm data, support wav、mp3、p3、pcm
""" """
if file_type == "p3": if file_type == "p3":
# 直接用p3解码 # 直接用p3解码
return p3.decode_opus_from_bytes_stream(audio_bytes, callback) return p3.decode_opus_from_bytes_stream(audio_bytes, callback)
elif file_type == "pcm":
audio = AudioSegment.from_raw(
BytesIO(audio_bytes),
)
else: else:
# 其他格式用pydub # other formats use pydub
audio = AudioSegment.from_file( audio = AudioSegment.from_file(
BytesIO(audio_bytes), format=file_type, parameters=["-nostdin"] BytesIO(audio_bytes), format=file_type, parameters=["-nostdin"]
) )
audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2) audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
raw_data = audio.raw_data raw_data = audio.raw_data
pcm_to_data_stream(raw_data, is_opus, callback) pcm_to_data_stream(raw_data, is_opus, callback)
def pcm_to_data_stream(raw_data, is_opus=True, callback: Callable[[Any], Any] = None): def pcm_to_data_stream(raw_data, is_opus=True, callback: Callable[[Any], Any] = None):