mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
fix: 解决音频每帧流畅播放的问题
This commit is contained in:
commit
cf8a815fb9
7 changed files with 46 additions and 36 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -147,3 +147,4 @@ tmp
|
|||
.env.development
|
||||
docker-compose.yml
|
||||
web/vue/node_modules
|
||||
/asr-models/
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ selected_module:
|
|||
# 将根据配置名称对应的type调用实际的LLM适配器
|
||||
LLM: ChatGLMLLM
|
||||
# TTS将根据配置名称对应的type调用实际的TTS适配器
|
||||
TTS: EdgeTTS
|
||||
TTS: FishSpeech
|
||||
|
||||
ASR:
|
||||
FunASR:
|
||||
|
|
@ -121,7 +121,7 @@ LLM:
|
|||
# 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
|
||||
model_name: glm-4-flash
|
||||
url: https://open.bigmodel.cn/api/paas/v4/
|
||||
api_key: 51ff5fdb325c4fc899923d532148c2dd.FFuMryUTTnf9fKRf
|
||||
api_key: 你的ChatGLMLLM api key
|
||||
OllamaLLM:
|
||||
# 定义LLM API类型
|
||||
type: ollama
|
||||
|
|
@ -162,7 +162,7 @@ LLM:
|
|||
api_key: 你的home assistant api访问令牌
|
||||
|
||||
TTS_SET:
|
||||
TTS_STREAM: false #是否启动流响应 true/false,默认false
|
||||
TTS_STREAM: true #是否启动流响应 true/false,默认false
|
||||
MAX_WORKERS: 4 #并发请求tts的数量,这个调太大,本地tts会变慢
|
||||
|
||||
TTS:
|
||||
|
|
@ -228,7 +228,7 @@ TTS:
|
|||
- "工钱,今天一起算,有磨能使鬼推钱。哎呀,你难倒我了,像我这么乖的小孩,怎么更乖。"
|
||||
normalize: true
|
||||
max_new_tokens: 1024
|
||||
chunk_length: 50
|
||||
chunk_length: 200
|
||||
top_p: 0.7
|
||||
repetition_penalty: 1.2
|
||||
temperature: 0.7
|
||||
|
|
|
|||
|
|
@ -103,12 +103,12 @@ async def handleIotDescriptors(conn, descriptors):
|
|||
descriptor["methods"])
|
||||
conn.iot_descriptors[descriptor["name"]] = iot_descriptor
|
||||
|
||||
# 暂时从配置文件中设置音量,后期通过意图识别控制音量
|
||||
default_iot_volume = 100
|
||||
if "iot" in conn.config:
|
||||
default_iot_volume = conn.config["iot"]["Speaker"]["volume"]
|
||||
logger.bind(tag=TAG).info(f"服务端设置音量为{default_iot_volume}")
|
||||
await send_iot_conn(conn, "Speaker", "SetVolume", {"volume": default_iot_volume})
|
||||
# TODO 暂时从配置文件中设置音量,后期通过意图识别控制音量
|
||||
# default_iot_volume = 100
|
||||
# if "iot" in conn.config:
|
||||
# default_iot_volume = conn.config["iot"]["Speaker"]["volume"]
|
||||
# logger.bind(tag=TAG).info(f"服务端设置音量为{default_iot_volume}")
|
||||
# await send_iot_conn(conn, "Speaker", "SetVolume", {"volume": default_iot_volume})
|
||||
|
||||
|
||||
async def send_iot_conn(conn, name, method_name, parameters):
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ async def sendAudioMessageStream(conn, audios_queue, text, text_index=0):
|
|||
|
||||
# 初始化流控参数
|
||||
frame_duration = 60 # 毫秒
|
||||
start_time = time.perf_counter() # 使用高精度计时器
|
||||
start_time = time.time() # 使用高精度计时器
|
||||
play_position = 0 # 已播放的时长(毫秒)
|
||||
time_out_stop = False
|
||||
while True:
|
||||
|
|
@ -57,7 +57,7 @@ async def sendAudioMessageStream(conn, audios_queue, text, text_index=0):
|
|||
last_duration = conn.tts_duration - queue_duration
|
||||
if 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:
|
||||
await conn.websocket.send(opus_packet)
|
||||
start_time = time.time() # 更新获取数据的时间
|
||||
|
|
|
|||
|
|
@ -94,13 +94,7 @@ class TTSProviderBase(ABC):
|
|||
|
||||
return opus_datas, duration
|
||||
|
||||
def wav_to_opus_data_audio(self, audio):
|
||||
duration = len(audio) / 1000.0
|
||||
# 转换为单声道和16kHz采样率(确保与编码器匹配)
|
||||
audio = audio.set_channels(1).set_frame_rate(16000)
|
||||
# 获取原始PCM数据(16位小端)
|
||||
raw_data = audio.raw_data
|
||||
|
||||
def wav_to_opus_data_audio_raw(self, raw_data):
|
||||
# 初始化Opus编码器
|
||||
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
|
||||
|
||||
|
|
@ -116,6 +110,7 @@ class TTSProviderBase(ABC):
|
|||
|
||||
# 如果最后一帧不足,补零
|
||||
if len(chunk) < frame_size * 2:
|
||||
# logger.bind(tag=TAG).info("开始补0")
|
||||
chunk += b'\x00' * (frame_size * 2 - len(chunk))
|
||||
|
||||
# 转换为numpy数组处理
|
||||
|
|
@ -125,4 +120,4 @@ class TTSProviderBase(ABC):
|
|||
opus_data = encoder.encode(np_frame.tobytes(), frame_size)
|
||||
opus_datas.append(opus_data)
|
||||
|
||||
return opus_datas, duration
|
||||
return opus_datas
|
||||
|
|
|
|||
|
|
@ -171,10 +171,10 @@ class TTSProvider(TTSProviderBase):
|
|||
with io.BytesIO() as bf:
|
||||
torchaudio.save(bf, tts_speech, 44100, 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
|
||||
|
||||
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):
|
||||
try:
|
||||
# Prepare reference data
|
||||
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
|
||||
|
|
@ -204,6 +204,8 @@ class TTSProvider(TTSProviderBase):
|
|||
pydantic_data = ServeTTSRequest(**data)
|
||||
audio_buff = None
|
||||
chunk_total = b''
|
||||
last_raw = b''
|
||||
audio_raw = b''
|
||||
print("请求tts")
|
||||
with requests.post(
|
||||
self.api_url,
|
||||
|
|
@ -217,30 +219,36 @@ class TTSProvider(TTSProviderBase):
|
|||
for chunk in response.iter_content():
|
||||
# 拼接当前块和上一块数据
|
||||
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)
|
||||
if not audio_buff:
|
||||
audio_buff = audio
|
||||
else:
|
||||
audio_buff += audio
|
||||
if len(audio_buff.raw_data) % 1920 == 0:
|
||||
# 把 audio 转成 opus
|
||||
opus_datas, duration = self.wav_to_opus_data_audio(audio_buff)
|
||||
audio_raw = audio_raw + audio.raw_data
|
||||
#长度凑够2贞开始发送,60ms*4=240ms
|
||||
if len(audio_raw) >= 7680:
|
||||
duration = 60 * len(audio_raw) // 1920
|
||||
if (len(audio_raw) % 1920) > 0:
|
||||
duration += 60
|
||||
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({
|
||||
"data": opus_datas,
|
||||
"duration": duration,
|
||||
"end": False,
|
||||
"text_index": text_index
|
||||
})
|
||||
audio_buff = None
|
||||
audio_raw = b''
|
||||
chunk_total = b''
|
||||
if len(chunk_total) > 0:
|
||||
if not audio_buff:
|
||||
audio_buff = self._get_audio_from_tts(chunk_total)
|
||||
else:
|
||||
audio_buff += self._get_audio_from_tts(chunk_total)
|
||||
audio = self._get_audio_from_tts(chunk_total)
|
||||
audio_raw = audio_raw + audio.raw_data
|
||||
duration = 60 * len(audio_raw) // 1920
|
||||
if (len(audio_raw) % 1920) > 0:
|
||||
duration += 60
|
||||
duration = duration / 1000.0
|
||||
# 把 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({
|
||||
"data": opus_datas,
|
||||
"duration": duration,
|
||||
|
|
|
|||
|
|
@ -35,6 +35,12 @@ def write_json_file(file_path, data):
|
|||
json.dump(data, file, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
def is_segment(tokens):
|
||||
if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":","?","、"):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def is_punctuation_or_emoji(char):
|
||||
"""检查字符是否为空格、指定标点或表情符号"""
|
||||
# 定义需要去除的中英文标点(包括全角/半角)
|
||||
|
|
|
|||
Loading…
Reference in a new issue