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

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- 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:
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")
# 初始化 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)
if __name__ == '__main__':
TEXT = '你好,听到你心情不好我很抱歉。可以告诉我是什么让你感到如此糟糕吗?有时候把烦恼说出来会让我们感觉好一些。无论发生了什么,我都会在这里认真倾听,和你一起面对。记住,每个困难都会过去,明天总是新的开始。'
t = TTS("tests/test_tts.mp3")
t.start(TEXT)