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.
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 threading
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 . _th = threading . Thread ( target = self . _run )
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 " )
self . _th . start ( )
def on_close ( self , * args ) :
if self . _f :
self . _f . close ( )
def on_data ( self , data , * args ) :
if self . _f :
self . _f . write ( data )
def _run ( self ) :
tts = nls . NlsSpeechSynthesizer (
url = URL ,
token = TOKEN ,
appkey = APPKEY ,
on_data = self . on_data ,
on_close = self . on_close
)
tts . start ( self . _text , voice = " xiaobei " , aformat = " mp3 " )
if __name__ == ' __main__ ' :
TEXT = ' 大壮正想去摘取花瓣,谁知阿丽和阿强突然内讧 '
t = TTS ( " tests/test_tts.mp3 " )
t . start ( TEXT )