1.到官网下载SDK并安装
2.测试代码如下:
import nls
import nls.speech_synthesizer
URL = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1"
TOKEN = "your_token" # 参考https://help.aliyun.com/document_detail/450255.html获取token
APPKEY = "your_appkey" # 获取Appkey请前往控制台:https://nls-portal.console.aliyun.com/applist
class MyTTS:
def on_metainfo(self, message, *args):
print("on_metainfo message=>{}".format(message))
def on_error(self, message, *args):
print("on_error args=>{}".format(args))
def on_close(self, *args):
print("on_close: args=>{}".format(args))
try:
self.__file.close()
except Exception as e:
print("close failed:", e)
def on_data(self, data, *args):
try:
self.__file.write(data)
except Exception as e:
print("write data failed:", e)
def on_completed(self, message, *args):
print("on_completed:args=>{} message=>{}".format(args, message))
def run(self, text, voice, file):
self.__file = open(file, "wb")
self.__text = text
self.__voice = voice
tts = nls.NlsSpeechSynthesizer(
url=URL,
token=TOKEN,
appkey=APPKEY,
on_metainfo=self.on_metainfo,
on_data=self.on_data,
on_completed=self.on_completed,
on_error=self.on_error,
on_close=self.on_close
)
result = tts.start(self.__text, voice=self.__voice, aformat="mp3")
print("tts done with result:{}".format(result))
voice_list = ["zhimiao_emo", "zhimi_emo", "zhiyan_emo", "xiaogang", "sicheng", "aicheng", "xiaoyun", "ruoxi", "aida",
"ninger", "ruilin", "siyue", "aiya", "aixia", "aiyu", "sitong", "xiaobei", "aiwei", "aibao"]
synthesizer = MyTTS()
# 每个声音都测试一下
for voice in voice_list:
synthesizer.run(text="这是测试用句", voice=voice, file=f"{voice}.mp3")