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.

47 lines
1.5 KiB

4 months ago
# -*- coding: utf-8 -*-
import nls
import os
from GetToken import *
URL = "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1"
TOKEN = getToken() # 参考https://help.aliyun.com/document_detail/450255.html获取token
APPKEY = "90RJcqjlN4ZqymGd" # 获取Appkey请前往控制台https://nls-portal.console.aliyun.com/applist
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
# 确保目录存在
os.makedirs(os.path.dirname(self._file), exist_ok=True)
self._f = open(self._file, "wb")
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:
self._f.write(data)
4 months ago
if __name__ == '__main__':
4 months ago
TEXT = '你好,听到你心情不好我很抱歉。可以告诉我是什么让你感到如此糟糕吗?有时候把烦恼说出来会让我们感觉好一些。无论发生了什么,我都会在这里认真倾听,和你一起面对。记住,每个困难都会过去,明天总是新的开始。'
4 months ago
t = TTS("tests/test_tts.mp3")
4 months ago
t.start(TEXT)