背景
我对语音合成系统还是很感兴趣的,总希望能够为自己合成一些内容,比如合成小说、播放我下载给我的电子书等等。
语音合成系统
或许它是一个基于语音合成的工具,而且由于很多厂商都提供了这个工具的API,所以开发难度大大增加。 您只需要调用几个API即可实现您自己的语音合成工具; 麻雀虽小,五脏俱全。 。 从更大的规模来看讯飞语音合成软件 v236 web版下载,这是一个大规模的语音合成系统。
去上班
首先我们需要将其安装到我们的笔记本电脑上
蟒蛇
Python3.7
视觉工作室代码
步
这里我们选择科大讯飞开放平台的WebAPI套接字。
首先我们到控制台创建一个应用程序

创建完成后,点击应用进入,会有应用的详细栏目。
点击一侧语音合成,进入下一关在线语音合成(流媒体版)

在右上臂讯飞语音合成软件 v236 web版下载,我们需要得到 3 个东西:
应用程序标识符
API秘密
API密钥
代码
好吧,让我们拿起它并实现代码。 首先,安装我们需要的两个库。
pip install websocket-clientpip install playsound
接下来我们定义一个类play,包含4个函数
class play:def __init__(self): #初始化函数def play_sound(self):#播放音频函数def select_vcn(self,*arg):#选择下拉框设置发音人def xfyun_tts(self):#进行语音合成
这里需要填写刚刚从科大讯飞开放平台控制台获取到的appid、appkey和appsecret
def __init__(self):self.APP_ID = 'xxx' #请填上自己的appidself.API_KEY = 'xxx' #请填上自己的appkeyself.SECRET_KEY = 'xxx' #请填上自己的appsecretself.root=tk.Tk() #初始化窗口self.root.title("语音合成系统") #窗口名称self.root.geometry("600x550") #设置窗口大小self.root.resizable(0,0)#self.root.resizable(width=True,height=True)#设置窗口是否可变,宽不可变,高可变,默认为Trueself.lb=tk.Label(self.root,text='请选择语音发音人')#标签self.tt=tk.Text(self.root,width=77,height=30) #多行文本框self.cb=ttk.Combobox(self.root, width=12) #下拉列表框#设置下拉列表框的内容self.cb['values']=("甜美女声-小燕","亲切男声-许久","知性女声-小萍", "可爱童声-许小宝","亲切女声-小婧")self.cb.current(0) #将当前选择状态置为0,也就是第一项self.cb.bind("<>" , self.select_vcn)self.tk_tts_file=tk.Label(self.root,text='生成文件名')self.b1=tk.Button(self.root, text='进行语音合成', width=10,height=1,command=self.xfyun_tts) #按钮self.tk_play=tk.Button(self.root, text='播放', width=10,height=1,command=self.play_sound) #按钮#各个组件的位置self.tk_tts_file.place(x=30,y=500)self.b1.place(x=300,y=500)self.tk_play.place(x=400,y=500)self.lb.place(x=30,y=30)self.cb.place(x=154,y=30)self.tt.place(x=30,y=60)self.root.mainloop()
当下拉列表被选中时,设置对应的扬声器
def select_vcn(self,*arg):if self.cb.get()=='甜美女声-小燕':self.vcn="xiaoyan"elif self.cb.get()=='亲切男声-许久':self.vcn="aisjiuxu"elif self.cb.get()=='知性女声-小萍':self.vcn="aisxping"elif self.cb.get()=='可爱童声-许小宝':self.vcn="aisbabyxu"elif self.cb.get()=='亲切女声-小婧':self.vcn="aisjinger"print(self.vcn)
接下来我们修改科大讯飞自带的Python demo,使其使用起来更加方便。
# -*- coding:utf-8 -*-## author: iflytek## 本demo测试时运行的环境为:Windows + Python3.7# 本demo测试成功运行时所安装的第三方库及其版本如下:# cffi==1.12.3# gevent==1.4.0# greenlet==0.4.15# pycparser==2.19# six==1.12.0# websocket==0.2.1# websocket-client==0.56.0# 合成小语种需要传输小语种文本、使用小语种发音人vcn、tte=unicode以及修改文本编码方式# 错误码链接:https://www.xfyun.cn/document/error-code (code返回错误码时必看)# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #import websocketimport datetimeimport hashlibimport base64import hmacimport jsonfrom urllib.parse import urlencodeimport timeimport sslfrom wsgiref.handlers import format_date_timefrom datetime import datetimefrom time import mktimeimport _thread as threadimport osimport waveSTATUS_FIRST_frame = 0 # 第一帧的标识STATUS_CONTINUE_frame = 1 # 中间帧标识STATUS_LAST_frame = 2 # 最后一帧的标识PCM_PATH = "./demo.pcm"class Ws_Param(object):# 初始化def __init__(self):passdef set_tts_params(self, text, vcn):if text != "":self.Text = textif vcn != "":self.vcn = vcn# 业务参数(business),更多个性化参数可在官网查看self.BusinessArgs = {"bgs":1,"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": self.vcn, "tte": "utf8"}#使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"”#self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")}self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}def set_params(self, appid, apiSecret, apiKey):if appid != "":self.APPID = appid# 公共参数(common)self.CommonArgs = {"app_id": self.APPID}if apiKey != "":self.APIKey = apiKeyif apiSecret != "":self.APISecret = apiSecret# 生成urldef create_url(self):url = 'wss://tts-api.xfyun.cn/v2/tts'# 生成RFC1123格式的时间戳now = datetime.now()date = format_date_time(mktime(now.timetuple()))# 拼接字符串signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"signature_origin += "date: " + date + "\n"signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"# 进行hmac-sha256进行加密signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),digestmod=hashlib.sha256).digest()signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha)authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')# 将请求的鉴权参数组合为字典v = {"authorization": authorization,"date": date,"host": "ws-api.xfyun.cn"}url = url + '?' + urlencode(v)return urldef on_message(ws, message):try:#print(message)try:message =json.loads(message)except Exception as e:print("111",e)code = message["code"]sid = message["sid"]audio = message["data"]["audio"]audio = base64.b64decode(audio)status = message["data"]["status"]print(code, sid, status)if status == 2:print("ws is closed")ws.close()if code != 0:errMsg = message["message"]print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))else:with open(PCM_PATH, 'ab') as f:f.write(audio)except Exception as e:print("receive msg,but parse exception:", e)# 收到websocket错误的处理def on_error(ws, error):print("### error:", error)# 收到websocket关闭的处理def on_close(ws):print("### closed ###")# 收到websocket连接建立的处理def on_open(ws):def run(*args):d = {"common": wsParam.CommonArgs,"business": wsParam.BusinessArgs,"data": wsParam.Data,}d = json.dumps(d)print("------>开始发送文本数据")ws.send(d)if os.path.exists(PCM_PATH):os.remove(PCM_PATH)thread.start_new_thread(run, ())def text2pcm(appid, apiSecret, apiKey, text, vcn, fname):wsParam.set_params(appid, apiSecret, apiKey)wsParam.set_tts_params(text, vcn)websocket.enableTrace(False)wsUrl = wsParam.create_url()ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)ws.on_open = on_openws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})pcm2wav(PCM_PATH, fname)def pcm2wav(fname, dstname):with open(fname, 'rb') as pcmfile:pcmdata = pcmfile.read()print(len(pcmdata))with wave.open(dstname, "wb") as wavfile:wavfile.setparams((1, 2, 16000, 0, 'NONE', 'NONE'))wavfile.writeframes(pcmdata)wsParam = Ws_Param()
最后实现了语音合成系统。

目前,各种云计算和云服务正在快速发展,各大公司提供了丰富的资源,这大大提高了人工智能发展的门槛。 您不需要了解语音合成原理,但可以快速开发语音合成工具!
inktype="text" imgurl="" imgdata="null" data-itemshowtype="11" tab="innerlink" data-linktype="2">那些让人直呼卧槽的Python代码!
inktype="text" imgurl="" imgdata="null" data-itemshowtype="0" tab="innerlink" data-linktype="2" wah-hotarea="click" style="outline: 0px;-webkit-tap-highlight-color: rgba(0, 0, 0, 0);cursor: pointer;max-width: 100%;box-sizing: border-box !important;overflow-wrap: break-word !important;">17个改变世界的数学公式!
inktype="text" imgurl="" imgdata="null" data-itemshowtype="11" tab="innerlink" data-linktype="2" wah-hotarea="click" hasload="1" style="outline: 0px;-webkit-tap-highlight-color: rgba(0, 0, 0, 0);cursor: pointer;max-width: 100%;box-sizing: border-box !important;overflow-wrap: break-word !important;">新一代 Python 包管理工具来了!
您看此文用 分 秒,转发只需1秒
下一篇: 杭州市“托育一件事”上线“浙里办”APP