This commit is contained in:
seven 2025-03-27 11:33:53 +08:00
parent 74700da91d
commit 3856f78fa2

View file

@ -8,7 +8,6 @@ import os
from pydub import AudioSegment from pydub import AudioSegment
import opuslib_next import opuslib_next
import numpy as np import numpy as np
from collections import deque
class TTSProvider(TTSProviderBase): class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file): def __init__(self, config, delete_audio_file):
@ -18,9 +17,9 @@ class TTSProvider(TTSProviderBase):
self.response_format = config.get("response_format") self.response_format = config.get("response_format")
self.sample_rate = config.get("sample_rate") self.sample_rate = config.get("sample_rate")
self.instruct_text = config.get("instruct_text") self.instruct_text = config.get("instruct_text")
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.cache_queue = deque(maxlen=30)
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}")
@ -41,6 +40,7 @@ class TTSProvider(TTSProviderBase):
} }
with open(output_file,'w',encoding='utf-8') as f: with open(output_file,'w',encoding='utf-8') as f:
f.write('http_post\n')
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)))
self.cache_queue.append(output_file) self.cache_queue.append(output_file)
@ -57,37 +57,42 @@ class TTSProvider(TTSProviderBase):
print(f"错误信息: {response.text}") print(f"错误信息: {response.text}")
def audio_to_opus_data(self, audio_file_path): def audio_to_opus_data(self, audio_file_path):
if audio_file_path in self.cache_queue:# os.path.exists('%s.linkerai'%audio_file_path): data = b''
duration = 100 if os.path.exists('%s.linkerai'%audio_file_path):
code = []
with open(audio_file_path,encoding='utf-8') as f: with open(audio_file_path,encoding='utf-8') as f:
for line in f.readlines(): data = f.read(10)
code.append(json.loads(line.strip())) if data.startswith('http_post'):
params = code[0] duration = 100
headers = code[1] code = []
return self.yield_data(params=params,headers=headers),duration for line in f.readlines():
else: # 兼容非流式音频播放 code.append(json.loads(line.strip()))
file_type = os.path.splitext(audio_file_path)[1] params = code[0]
if file_type: headers = code[1]
file_type = file_type.lstrip('.') return self.yield_data(params=params,headers=headers),duration
audio = AudioSegment.from_file(audio_file_path, format=file_type, parameters=["-nostdin"])
audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2) if not data.startswith('http_post'):# 兼容非流式音频播放
duration = len(audio) / 1000.0 f.seek(0)
raw_data = audio.raw_data file_type = os.path.splitext(audio_file_path)[1]
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO) if file_type:
frame_duration = 60 # 60ms per frame file_type = file_type.lstrip('.')
frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame audio = AudioSegment.from_file(audio_file_path, format=file_type, parameters=["-nostdin"])
opus_datas = [] audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample duration = len(audio) / 1000.0
chunk = raw_data[i:i + frame_size * 2] raw_data = audio.raw_data
if len(chunk) < frame_size * 2: encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
chunk += b'\x00' * (frame_size * 2 - len(chunk)) frame_duration = 60 # 60ms per frame
np_frame = np.frombuffer(chunk, dtype=np.int16) frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame
opus_data = encoder.encode(np_frame.tobytes(), frame_size)
opus_datas.append(opus_data) opus_datas = []
return opus_datas, duration for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample
chunk = raw_data[i:i + frame_size * 2]
if len(chunk) < frame_size * 2:
chunk += b'\x00' * (frame_size * 2 - len(chunk))
np_frame = np.frombuffer(chunk, dtype=np.int16)
opus_data = encoder.encode(np_frame.tobytes(), frame_size)
opus_datas.append(opus_data)
return opus_datas, duration
if __name__ == "__main__": if __name__ == "__main__":
config = {'access_token':'123', config = {'access_token':'123',