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

4 months ago
# -*- coding: utf-8 -*-
import nls
from GetToken import *
4 months ago
from TtsConfig import *
4 months ago
URL = "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1"
class TTS:
4 months ago
def __init__(self, _file):
4 months ago
self._file = _file
self._f = None
def start(self, text):
self._text = text
# 确保目录存在
4 months ago
# os.makedirs(os.path.dirname(self._file), exist_ok=True)
4 months ago
self._f = open(self._file, "wb")
4 months ago
TOKEN = getToken() # 参考https://help.aliyun.com/document_detail/450255.html获取token
4 months ago
# 初始化 TTS
4 months ago
tts = nls.NlsSpeechSynthesizer(
url=URL,
token=TOKEN,
appkey=APPKEY,
on_data=self.on_data,
on_close=self.on_close
)
4 months ago
# 同步执行 TTS 生成
4 months ago
tts.start(self._text, voice="xiaobei", aformat="mp3")
4 months ago
def on_close(self, *args):
if self._f:
self._f.close()
print("TTS 生成完成,文件已关闭")
def on_data(self, data, *args):
if self._f:
4 months ago
self._f.write(data)