1. 概述
使用queue,producer不断向queue中添加audio,然后consumer不断从queue中消费audio。
下面的样例使用melo来生成语音,需要先下载melo.tts。模型在https://myshell-public-repo-hosting.s3.amazonaws.com/openvoice/basespeakers/ZH/checkpoint.pth,config在https://myshell-public-repo-hosting.s3.amazonaws.com/openvoice/basespeakers/ZH/config.json。
2. 代码部分
from melo import utils
from melo.models import SynthesizerTrn
from melo.split_utils import split_sentences_zh
from melo.download_utils import load_or_download_config, load_or_download_model
from queue import Queue
from threading import Thread
import numpy as np
from pydub import playback
import torch, audiosegment
device = 'mps'
hps = load_or_download_config('ZH', use_hf=True, config_path=None)
num_languages = hps.num_languages
num_tones = hps.num_tones
symbols = hps.symbols
model = SynthesizerTrn(len(symbols),hps.data.filter_length // 2 + 1,hps.train.segment_size // hps.data.hop_length,n_speakers=hps.data.n_speakers,num_tones=num_tones,num_languages=num_languages,**hps.model,).to(device)
model.eval()
symbol_to_id = {s: i for i, s in enumerate(symbols)}
checkpoint_dict = load_or_download_model('ZH', device, use_hf=True, ckpt_path=None)
model.load_state_dict(checkpoint_dict['model'], strict=True)
def play(text):
texts = text.split('。')
speaker_id = 1
def producer(queue):
for i,t in enumerate(texts):
bert, ja_bert, phones, tones, lang_ids = utils.get_text_for_tts_infer(t, 'ZH_MIX_EN', hps, device, symbol_to_id)
with torch.no_grad():
x_tst = phones.to(device).unsqueeze(0)
tones = tones.to(device).unsqueeze(0)
lang_ids = lang_ids.to(device).unsqueeze(0)
bert = bert.to(device).unsqueeze(0)
ja_bert = ja_bert.to(device).unsqueeze(0)
x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
del phones
speakers = torch.LongTensor([speaker_id]).to(device)
audio = model.infer(x_tst,x_tst_lengths,speakers,tones,lang_ids,bert,ja_bert,
sdp_ratio=0,noise_scale=0,noise_scale_w=0,length_scale=1,)[0][0, 0].data.cpu().float().numpy()
del x_tst, tones, lang_ids, bert, ja_bert, x_tst_lengths, speakers
queue.put(audio)
def consumer(queue):
while True:
audio = queue.get()
playback.play(audiosegment.from_numpy_array(audio.astype(np.float32),hps.data.sampling_rate))
queue.task_done()
q = Queue()
q.put(np.zeros(int(hps.data.sampling_rate * 0.1)))
t1 = Thread(target = producer, args=(q,))
t2 = Thread(target=consumer, args=(q,))
t2.daemon = True # 线程2是无限循环需要设置守护线程以便主线程退出
t1.start()
t2.start()
t1.join() # 等待所有项被生产
q.join() # 等待所有项被消费
text = "..."
play(text)