mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-07-31 03:43:57 +08:00
update:优化
This commit is contained in:
@@ -2,12 +2,12 @@ import os
|
||||
import uuid
|
||||
import requests
|
||||
from datetime import datetime
|
||||
|
||||
from pydub import AudioSegment
|
||||
|
||||
from core.providers.tts.dto.dto import TTSMessageDTO, MsgType, SentenceType
|
||||
from core.utils.util import check_model_key
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
from config.logger import setup_logging
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class TTSProvider(TTSProviderBase):
|
||||
@@ -35,8 +35,7 @@ class TTSProvider(TTSProviderBase):
|
||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
||||
)
|
||||
|
||||
async def text_to_speak(self, u_id, text, is_last_text=False, is_first_text=False):
|
||||
tmp_file = self.generate_filename()
|
||||
async def text_to_speak(self, text, output_file):
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
@@ -50,26 +49,9 @@ class TTSProvider(TTSProviderBase):
|
||||
}
|
||||
response = requests.post(self.api_url, json=data, headers=headers)
|
||||
if response.status_code == 200:
|
||||
with open(tmp_file, "wb") as audio_file:
|
||||
with open(output_file, "wb") as audio_file:
|
||||
audio_file.write(response.content)
|
||||
else:
|
||||
raise Exception(
|
||||
f"OpenAI TTS请求失败: {response.status_code} - {response.text}"
|
||||
)
|
||||
# 使用 pydub 读取临时文件
|
||||
audio = AudioSegment.from_file(tmp_file, format="wav")
|
||||
audio = audio.set_channels(1).set_frame_rate(16000)
|
||||
opus_datas = self.wav_to_opus_data_audio_raw(audio.raw_data)
|
||||
yield TTSMessageDTO(
|
||||
u_id=u_id,
|
||||
msg_type=MsgType.TTS_TEXT_RESPONSE,
|
||||
content=opus_datas,
|
||||
tts_finish_text=text,
|
||||
sentence_type=SentenceType.SENTENCE_START,
|
||||
)
|
||||
# 用完后删除临时文件
|
||||
try:
|
||||
os.remove(tmp_file)
|
||||
except FileNotFoundError:
|
||||
# 若文件不存在,忽略该异常
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user