This commit is contained in:
seven 2025-03-28 15:14:58 +08:00
parent a11126361a
commit 82893f589c
2 changed files with 44 additions and 4 deletions

View file

@ -10,6 +10,9 @@ logger = setup_logging()
async def sendAudioMessage(conn, audios, text, text_index=0): async def sendAudioMessage(conn, audios, text, text_index=0):
if text_index == -1:
await sendAudioStream(conn=conn,audios=audios)
return
# 发送句子开始消息 # 发送句子开始消息
if text_index == conn.tts_first_text_index: if text_index == conn.tts_first_text_index:
logger.bind(tag=TAG).info(f"发送第一段语音: {text}") logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
@ -26,6 +29,41 @@ async def sendAudioMessage(conn, audios, text, text_index=0):
if conn.close_after_chat: if conn.close_after_chat:
await conn.close() await conn.close()
async def sendAudioStream(conn, audios):
# 流控参数优化
frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码
start_time = time.perf_counter()
play_position = 0
if isinstance(audios,types.GeneratorType):
count = 0
for opus_packet in audios:
if opus_packet.startswith(b'text:'):
await send_tts_message(conn, "sentence_start", opus_packet.replace(b'text:','').decode('utf-8'))
continue
if len(opus_packet) < 1:
continue
if count < 3:
await conn.websocket.send(opus_packet)
conn.logger.bind(tag=TAG).debug(f"预缓冲帧 {count}, 时间: {(time.perf_counter() - start_time) * 1000:.2f}ms")
else:
if conn.client_abort:
return
expected_time = start_time + (play_position / 1000)
current_time = time.perf_counter()
delay = expected_time - current_time
if delay > 0:
await asyncio.sleep(delay)
await conn.websocket.send(opus_packet)
conn.logger.bind(tag=TAG).debug(f"发送帧,位置: {play_position}ms, 实际间隔: {(time.perf_counter() - current_time) * 1000:.2f}ms")
play_position += frame_duration
count += 1
await send_tts_message(conn, 'stop', None)
if conn.close_after_chat:
await conn.close()
# 播放音频 # 播放音频
async def sendAudio(conn, audios): async def sendAudio(conn, audios):
# 流控参数优化 # 流控参数优化

View file

@ -21,6 +21,7 @@ class TTSProvider(TTSProviderBase):
self.stream_mode = config.get('stream_mode') # stream or double_stream self.stream_mode = config.get('stream_mode') # stream or double_stream
self.host = "tts.linkerai.top" self.host = "tts.linkerai.top"
self.api_url = 'http://tts.linkerai.top:24003/tts' self.api_url = 'http://tts.linkerai.top:24003/tts'
self.double_stream_url = 'http://tts.linkerai.top:24003/double_stream_chat'
def generate_filename(self, extension=".wav"): def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
@ -45,8 +46,8 @@ class TTSProvider(TTSProviderBase):
f.write('%s\n'%(json.dumps(params,ensure_ascii=False))) f.write('%s\n'%(json.dumps(params,ensure_ascii=False)))
f.write('%s'%(json.dumps(headers,ensure_ascii=False))) f.write('%s'%(json.dumps(headers,ensure_ascii=False)))
def yield_data(self,params,headers): def yield_data(self,url,params,headers):
response = requests.get(self.api_url, headers=headers, params=params, stream=True) response = requests.get(url, headers=headers, params=params, stream=True)
if response.status_code == 200: if response.status_code == 200:
for chunk in response.iter_content(chunk_size=None): for chunk in response.iter_content(chunk_size=None):
if chunk: if chunk:
@ -54,6 +55,7 @@ class TTSProvider(TTSProviderBase):
else: else:
print(f"请求失败,状态码: {response.status_code}") print(f"请求失败,状态码: {response.status_code}")
print(f"错误信息: {response.text}") print(f"错误信息: {response.text}")
def double_stream(self,question:str='',device_id:str=''): def double_stream(self,question:str='',device_id:str=''):
params = { params = {
"question": question, "question": question,
@ -65,7 +67,7 @@ class TTSProvider(TTSProviderBase):
"Authorization": f"Bearer {self.access_token}", "Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json" "Content-Type": "application/json"
} }
return self.yield_data(params=params,headers=headers) return self.yield_data(url=self.double_stream_url,params=params,headers=headers)
def audio_to_opus_data(self, audio_file_path): def audio_to_opus_data(self, audio_file_path):
@ -80,7 +82,7 @@ class TTSProvider(TTSProviderBase):
code.append(json.loads(line.strip())) code.append(json.loads(line.strip()))
params = code[0] params = code[0]
headers = code[1] headers = code[1]
return self.yield_data(params=params,headers=headers),duration return self.yield_data(self.api_url,params=params,headers=headers),duration
if not data.startswith('http_post'):# 兼容非流式音频播放 if not data.startswith('http_post'):# 兼容非流式音频播放
f.seek(0) f.seek(0)