Files
audio2motion/scripts/ali_tts.py
T

145 lines
4.9 KiB
Python

# -*- coding: utf-8 -*-
"""
* Copyright 2015 Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
from multiprocessing import Process, Pool
import json
import random
import uuid
import os
import librosa
import ali_speech
from ali_speech.callbacks import SpeechSynthesizerCallback
from ali_speech.constant import TTSFormat
from ali_speech.constant import TTSSampleRate
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
class MyCallback(SpeechSynthesizerCallback):
# 参数name用于指定保存音频的文件
def __init__(self, name):
self._name = name
self._fout = open(name, 'wb')
def on_binary_data_received(self, raw):
# print('MyCallback.on_binary_data_received: %s' % len(raw))
self._fout.write(raw)
def on_completed(self, message):
# print('MyCallback.OnRecognitionCompleted: %s' % message)
self._fout.close()
def on_task_failed(self, message):
print('MyCallback.OnRecognitionTaskFailed-task_id:%s, status_text:%s' % (message['header']['task_id'], message['header']['status_text']))
self._fout.close()
os.remove(self._name)
def on_channel_closed(self):
# print('MyCallback.OnRecognitionChannelClosed')
pass
def on_close(self, a, b, c):
pass
def process(client, appkey, token, text, audio_name, voice, volume, pitch, speed):
voices = ["aixia", "stella"]
#voices = ["maoxiaomei", "aifei", "yaqun", "qiaowei", "laotie", "laomei"]
#voices = ["xiaoyun","xiaogang","ruoxi","siqi","sijia","sicheng","aiqi","aijia","aicheng","aida","ninger","ruilin","siyue","aiya","aixia","aimei","aiyu","aiyue","aijing","xiaomei","sijing","aishuo","guijie","stella","stanley","kenny","rosa","xiaoxian","maoxiaomei","aifei"]
# voices = ['aikan']
callback = MyCallback(audio_name)
synthesizer = client.create_synthesizer(callback)
synthesizer.set_appkey(appkey)
synthesizer.set_token(token)
synthesizer.set_voice(voices[voice])
synthesizer.set_text(text)
synthesizer.set_format(TTSFormat.WAV)
synthesizer.set_sample_rate(TTSSampleRate.SAMPLE_RATE_16K)
synthesizer.set_volume(volume)
synthesizer.set_speech_rate(speed)
synthesizer.set_pitch_rate(pitch)
try:
ret = synthesizer.start()
if ret < 0:
return ret
synthesizer.wait_completed()
except Exception as e:
print(e)
finally:
synthesizer.close()
if os.path.exists(audio_name):
duration = round(librosa.get_duration(filename=audio_name), 2)
return {'audio_filepath': audio_name, 'duration': duration, 'text': text}
return None
def process_multiprocess(number, repeat, texts, export_dir, json_file):
client = ali_speech.NlsClient()
# 设置输出日志信息的级别:DEBUG、INFO、WARNING、ERROR
client.set_log_level('INFO')
ali_client = AcsClient(
"LTAIUkF55OIJw7Q8",
"a2OxoUuAQ4gbT2FkqpfiPfXgpPp7dh",
"cn-shanghai"
)
# 创建request,并设置参数
request = CommonRequest()
request.set_method('POST')
request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
request.set_version('2019-02-28')
request.set_action_name('CreateToken')
response = ali_client.do_action_with_exception(request)
response = json.loads(response)
token = response["Token"]["Id"]
appkey = 'vxDWVWpU2V2nwPhK'
pool = Pool(processes=number)
result = []
for text in texts:
for _ in range(repeat): # repeat syn time
audio_name = os.path.join(export_dir, ''.join(str(uuid.uuid4()).split('-')) + ".wav")
voice = random.randint(0, 5)
#voice = 4
volume = random.randint(25, 75)
pitch = random.randint(-50, 50)
speed = random.randint(-125, 166)
result.append(pool.apply_async(process,(client, appkey, token, text, audio_name, voice, volume, pitch, speed)))
pool.close()
pool.join()
with open(json_file, 'w') as f:
for res in result:
line = res.get()
if line is not None:
f.write(json.dumps(line, ensure_ascii=False)+'\n')
if __name__ == "__main__":
texts = open('/mfs/dylan/tts/tts_text.txt').read().splitlines()
export_dir = '/mfs/dylan/tts/wav_john/'
json_file = '/mfs/dylan/tts/tts_data_john.json'
process_num = 30
repeat_num = 10
process_multiprocess(process_num, repeat_num, texts, export_dir, json_file)