fix: 解决音频每帧流畅播放的问题

This commit is contained in:
lizhongxiang 2025-03-05 14:48:21 +08:00
parent 2b87ab2d00
commit 160a9f6f52
4 changed files with 28 additions and 25 deletions

View file

@ -236,7 +236,7 @@ TTS:
- "工钱,今天一起算,有磨能使鬼推钱。哎呀,你难倒我了,像我这么乖的小孩,怎么更乖。" - "工钱,今天一起算,有磨能使鬼推钱。哎呀,你难倒我了,像我这么乖的小孩,怎么更乖。"
normalize: true normalize: true
max_new_tokens: 1024 max_new_tokens: 1024
chunk_length: 50 chunk_length: 200
top_p: 0.7 top_p: 0.7
repetition_penalty: 1.2 repetition_penalty: 1.2
temperature: 0.7 temperature: 0.7

View file

@ -57,7 +57,7 @@ async def sendAudioMessageStream(conn, audios_queue, text, text_index=0):
last_duration = conn.tts_duration - queue_duration last_duration = conn.tts_duration - queue_duration
if last_duration <= 0: if last_duration <= 0:
last_duration = 0 last_duration = 0
conn.tts_duration = duration + last_duration + 0.5 conn.tts_duration = duration + last_duration
for opus_packet in audio_opus_datas: for opus_packet in audio_opus_datas:
await conn.websocket.send(opus_packet) await conn.websocket.send(opus_packet)
start_time = time.time() # 更新获取数据的时间 start_time = time.time() # 更新获取数据的时间

View file

@ -94,13 +94,7 @@ class TTSProviderBase(ABC):
return opus_datas, duration return opus_datas, duration
def wav_to_opus_data_audio(self, audio): def wav_to_opus_data_audio_raw(self, raw_data):
duration = len(audio) / 1000.0
# 转换为单声道和16kHz采样率(确保与编码器匹配)
audio = audio.set_channels(1).set_frame_rate(16000)
# 获取原始PCM数据(16位小端)
raw_data = audio.raw_data
# 初始化Opus编码器 # 初始化Opus编码器
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO) encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
@ -116,6 +110,7 @@ class TTSProviderBase(ABC):
# 如果最后一帧不足,补零 # 如果最后一帧不足,补零
if len(chunk) < frame_size * 2: if len(chunk) < frame_size * 2:
# logger.bind(tag=TAG).info("开始补0")
chunk += b'\x00' * (frame_size * 2 - len(chunk)) chunk += b'\x00' * (frame_size * 2 - len(chunk))
# 转换为numpy数组处理 # 转换为numpy数组处理
@ -125,4 +120,4 @@ class TTSProviderBase(ABC):
opus_data = encoder.encode(np_frame.tobytes(), frame_size) opus_data = encoder.encode(np_frame.tobytes(), frame_size)
opus_datas.append(opus_data) opus_datas.append(opus_data)
return opus_datas, duration return opus_datas

View file

@ -171,7 +171,7 @@ class TTSProvider(TTSProviderBase):
with io.BytesIO() as bf: with io.BytesIO() as bf:
torchaudio.save(bf, tts_speech, 44100, format="wav") torchaudio.save(bf, tts_speech, 44100, format="wav")
audio = AudioSegment.from_file(bf, format="wav") audio = AudioSegment.from_file(bf, format="wav")
audio.set_channels(1).set_frame_rate(16000) audio = audio.set_channels(1).set_frame_rate(16000)
return audio return audio
async def text_to_speak_stream(self, text, queue: queue.Queue, text_index=0): async def text_to_speak_stream(self, text, queue: queue.Queue, text_index=0):
@ -204,6 +204,8 @@ class TTSProvider(TTSProviderBase):
pydantic_data = ServeTTSRequest(**data) pydantic_data = ServeTTSRequest(**data)
audio_buff = None audio_buff = None
chunk_total = b'' chunk_total = b''
last_raw = b''
audio_raw = b''
print("请求tts") print("请求tts")
with requests.post( with requests.post(
self.api_url, self.api_url,
@ -217,30 +219,36 @@ class TTSProvider(TTSProviderBase):
for chunk in response.iter_content(): for chunk in response.iter_content():
# 拼接当前块和上一块数据 # 拼接当前块和上一块数据
chunk_total += chunk chunk_total += chunk
if len(chunk_total) >= 86400 and len(chunk_total) % 86400 == 0: # 最后一个是静音,说明是一个完整的音频
if len(chunk_total) % 2 == 0 and chunk_total[-2:] == b'\x00\x00':
audio = self._get_audio_from_tts(chunk_total) audio = self._get_audio_from_tts(chunk_total)
if not audio_buff: audio_raw = audio_raw + audio.raw_data
audio_buff = audio #长度凑够2贞开始发送,60ms*4=240ms
else: if len(audio_raw) >= 7680:
audio_buff = audio_buff.append(audio, crossfade=10) duration = 60 * len(audio_raw) // 1920
if len(audio_buff.raw_data) % 1920 == 0: if (len(audio_raw) % 1920) > 0:
# 把 audio 转成 opus duration += 60
opus_datas, duration = self.wav_to_opus_data_audio(audio_buff) duration = duration / 1000.0
logger.bind(tag=TAG).info(f'发送数据长度:{len(audio_raw)}')
opus_datas = self.wav_to_opus_data_audio_raw(audio_raw)
queue.put({ queue.put({
"data": opus_datas, "data": opus_datas,
"duration": duration, "duration": duration,
"end": False, "end": False,
"text_index": text_index "text_index": text_index
}) })
audio_buff = None audio_raw = b''
chunk_total = b'' chunk_total = b''
if len(chunk_total) > 0: if len(chunk_total) > 0:
if not audio_buff: audio = self._get_audio_from_tts(chunk_total)
audio_buff = self._get_audio_from_tts(chunk_total) audio_raw = audio_raw + audio.raw_data
else: duration = 60 * len(audio_raw) // 1920
audio_buff = audio_buff.append(self._get_audio_from_tts(chunk_total), crossfade=10) if (len(audio_raw) % 1920) > 0:
duration += 60
duration = duration / 1000.0
# 把 audio 转成 opus # 把 audio 转成 opus
opus_datas, duration = self.wav_to_opus_data_audio(audio_buff) logger.bind(tag=TAG).info(f'发送数据长度:{len(audio_raw)}')
opus_datas = self.wav_to_opus_data_audio_raw(audio_raw)
queue.put({ queue.put({
"data": opus_datas, "data": opus_datas,
"duration": duration, "duration": duration,