怎么用Python打造一個語音合成系統(tǒng)

今天小編給大家分享一下怎么用Python打造一個語音合成系統(tǒng)的相關(guān)知識點,內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

創(chuàng)新互聯(lián)專注于張北企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站開發(fā),商城建設(shè)。張北網(wǎng)站建設(shè)公司,為張北等地區(qū)提供建站服務(wù)。全流程按需網(wǎng)站開發(fā),專業(yè)設(shè)計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

語音合成系統(tǒng)

其實就是一個基于語音合成的工具,但是這個東西由于很多廠家都提供了API的形式,因此開發(fā)難度大大降低,只需要調(diào)用幾個API即可實現(xiàn)屬于自己的語音合成工具;麻雀雖小,五臟俱全。往大了說,這就是一個小型的語音合成系統(tǒng)。

準(zhǔn)備工作

首先我們電腦上需要安裝

  1. Anaconda

  2. Python 3.7

  3. visual studio code

步驟

這里我們選用訊飛開放平臺的WebAPI接口。

首先我們到控制臺創(chuàng)建一個應(yīng)用

怎么用Python打造一個語音合成系統(tǒng)

創(chuàng)建好了之后,點擊該應(yīng)用進(jìn)入,有該應(yīng)用的詳細(xì)欄目。

點擊左側(cè)的語音合成,再到下一級在線語音合成(流式版)

怎么用Python打造一個語音合成系統(tǒng)

在右上側(cè),我們需要拿到3個東西:

  1. APPID

  2. APISecret

  3. APIKey

代碼實現(xiàn)

好了接下來進(jìn)行代碼實現(xiàn)了,首先安裝我們需要的兩個庫。

pip install websocket-client
pip install playsound

接下來我們定義一個類play,包含4個函數(shù)

class play:
 def __init__(self): #初始化函數(shù)
 def play_sound(self):#播放音頻函數(shù)
 def select_vcn(self,*arg):#選擇下拉框設(shè)置發(fā)音人
 def xfyun_tts(self):#進(jìn)行語音合成

在這里,大家需要填上剛才從訊飛開放平臺控制臺獲取到的appid、appkey以及appsecret

def __init__(self):
 self.APP_ID = 'xxx' #請?zhí)钌献约旱腶ppid
 self.API_KEY = 'xxx'#請?zhí)钌献约旱腶ppkey
 self.SECRET_KEY = 'xxx' #請?zhí)钌献约旱腶ppsecret
 self.root=tk.Tk() #初始化窗口
 self.root.title("語音合成系統(tǒng)") #窗口名稱
 self.root.geometry("600x550") #設(shè)置窗口大小
 self.root.resizable(0,0)
 #self.root.resizable(width=True,height=True)#設(shè)置窗口是否可變,寬不可變,高可變,默認(rèn)為True
 self.lb=tk.Label(self.root,text='請選擇語音發(fā)音人')#標(biāo)簽
 self.tt=tk.Text(self.root,width=77,height=30) #多行文本框
 self.cb=ttk.Combobox(self.root, width=12)#下拉列表框
#設(shè)置下拉列表框的內(nèi)容
 self.cb['values']=("甜美女聲-小燕","親切男聲-許久","知性女聲-小萍", "可愛童聲-許小寶","親切女聲-小婧")
 self.cb.current(0)#將當(dāng)前選擇狀態(tài)置為0,也就是第一項
 self.cb.bind("<>", self.select_vcn)
 self.tk_tts_file=tk.Label(self.root,text='生成文件名')
 self.b1=tk.Button(self.root, text='進(jìn)行語音合成', 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()

當(dāng)選擇了下拉列表,設(shè)置對應(yīng)的發(fā)音人

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為從而更加方便的來使用。另外,搜索公眾號程序員小樂后臺回復(fù)“賺錢”,獲取一份驚喜禮包。

# -*- coding:utf-8 -*-
#
# author: iflytek
#
#本demo測試時運行的環(huán)境為: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
# 合成小語種需要傳輸小語種文本、使用小語種發(fā)音人vcn、tte=unicode以及修改文本編碼方式
#錯誤碼鏈接:https://www.xfyun.cn/document/error-code (code返回錯誤碼時必看)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import websocket
import datetime
import hashlib
import base64
import hmac
import json
from urllib.parse import urlencode
import time
import ssl
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
import _thread as thread
import os
import wave
STATUS_FIRST_FRAME = 0# 第一幀的標(biāo)識
STATUS_CONTINUE_FRAME = 1# 中間幀標(biāo)識
STATUS_LAST_FRAME = 2# 最后一幀的標(biāo)識
PCM_PATH = "./demo.pcm"
class Ws_Param(object):
 # 初始化
 def __init__(self):
 pass
 def set_tts_params(self, text, vcn):
 if text != "":
 self.Text = text
 if vcn != "":
 self.vcn = vcn
 # 業(yè)務(wù)參數(shù)(business),更多個性化參數(shù)可在官網(wǎng)查看
 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
 # 公共參數(shù)(common)
 self.CommonArgs = {"app_id": self.APPID}

 if apiKey != "":
 self.APIKey = apiKey

 if apiSecret != "":
 self.APISecret = apiSecret
 # 生成url
 def 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"
 # 進(jìn)行hmac-sha256進(jìn)行加密
 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')
 # 將請求的鑒權(quán)參數(shù)組合為字典
 v = {
 "authorization": authorization,
 "date": date,
 "host": "ws-api.xfyun.cn"
 }

 url = url + '?' + urlencode(v)

 return url
def 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關(guān)閉的處理
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("------>開始發(fā)送文本數(shù)據(jù)")
 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_open
 ws.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()

最終一個語音合成系統(tǒng)就這樣實現(xiàn)了。

怎么用Python打造一個語音合成系統(tǒng)

以上就是“怎么用Python打造一個語音合成系統(tǒng)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)頁名稱:怎么用Python打造一個語音合成系統(tǒng)
文章路徑:http://muchs.cn/article24/pipcce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、小程序開發(fā)微信小程序、微信公眾號搜索引擎優(yōu)化、ChatGPT

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)