You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1.1 KiB
37 lines
1.1 KiB
# -*- coding: utf-8 -*-
|
|
import nls
|
|
from GetToken import *
|
|
from TtsConfig import *
|
|
URL = "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1"
|
|
|
|
class TTS:
|
|
def __init__(self, _file):
|
|
self._file = _file
|
|
self._f = None
|
|
|
|
def start(self, text):
|
|
self._text = text
|
|
# 确保目录存在
|
|
# os.makedirs(os.path.dirname(self._file), exist_ok=True)
|
|
self._f = open(self._file, "wb")
|
|
TOKEN = getToken() # 参考https://help.aliyun.com/document_detail/450255.html获取token
|
|
# 初始化 TTS
|
|
tts = nls.NlsSpeechSynthesizer(
|
|
url=URL,
|
|
token=TOKEN,
|
|
appkey=APPKEY,
|
|
on_data=self.on_data,
|
|
on_close=self.on_close
|
|
)
|
|
|
|
# 同步执行 TTS 生成
|
|
tts.start(self._text, voice="xiaobei", aformat="mp3")
|
|
|
|
def on_close(self, *args):
|
|
if self._f:
|
|
self._f.close()
|
|
print("TTS 生成完成,文件已关闭")
|
|
|
|
def on_data(self, data, *args):
|
|
if self._f:
|
|
self._f.write(data) |