<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

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

          共 8000字,需瀏覽 16分鐘

           ·

          2022-03-08 07:03



          背景


          一直對語音合成系統(tǒng)比較感興趣,總想能給自己合成一點內(nèi)容,比如說合成小說,把我下載的電子書播報給我聽等等。



          語音合成系統(tǒng)


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


          準備工作


          首先我們電腦上需要安裝


          • Anaconda

          • Python 3.7

          • visual studio code


          步驟


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


          https://www.xfyun.cn/doc/tts/online_tts/API.html


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


          創(chuàng)建好了之后,點擊該應用進入,有該應用的詳細欄目。(我這里創(chuàng)建了一個名為myaibot的應用)點擊左側的語音合成,再到下一級在線語音合成(流式版)



          在右上側,能夠看到我們需要拿到3個東西:


          • APPID

          • APISecret

          • APIKey


          有了這3個關鍵信息,我們就可以開始使用訊飛在線語音合成來打造我們的系統(tǒng)了。


          代碼實現(xiàn)


          接下來終于到了代碼實現(xiàn)環(huán)節(jié)了。首先安裝我們需要的兩個庫


          pip install websocket-clientpip install playsound


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


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


          大家需要填上剛才從訊飛開放平臺控制臺獲取到的appid、apikey以及apisecret。另外,搜索公眾號技術社區(qū)后臺回復“壁紙”,獲取一份驚喜禮包。


          def __init__(self):    self.vcn = 'xiaoyan'    self.APP_ID = 'xxx'# 請?zhí)钌献约旱腶ppid    self.API_KEY = 'xxx'# 請?zhí)钌献约旱腶ppkey????self.SECRET_KEY?=?'xxx'?#?請?zhí)钌献约旱腶ppsecret
          self.fname = ""
          self.root = tk.Tk() # 初始化窗口 self.root.title("語音合成系統(tǒng)") # 窗口名稱 self.root.geometry("600x550") # 設置窗口大小 self.root.resizable(0, 0) # 為了方便固定窗口大小 self.tk_lb = tk.Label(self.root, text='請選擇語音發(fā)音人') # 標簽 self.tk_text = tk.Text(self.root, width=77, height=30) # 多行文本框 self.tk_cb_vcn = ttk.Combobox(self.root, width=12) # 下拉列表框 # 設置下拉列表框的內(nèi)容 self.tk_cb_vcn['values'] = ("甜美女聲-小燕", "親切男聲-許久", "知性女聲-小萍", "可愛童聲-許小寶", "親切女聲-小婧") self.tk_cb_vcn.current(0) # 將當前選擇狀態(tài)置為0,也就是第一項 self.tk_cb_vcn.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.tk_lb.place(x=30, y=30) self.tk_cb_vcn.place(x=154, y=30)

          self.tk_text.place(x=30, y=60) self.root.mainloop()


          當選擇了下拉列表,設置對應的發(fā)音人


          def select_vcn(self, *args):        if self.tk_cb_vcn.get() == '甜美女聲-小燕':            self.vcn = "xiaoyan"        elif self.tk_cb_vcn.get() == '親切男聲-許久':            self.vcn = "aisjiuxu"        elif self.tk_cb_vcn.get() == '知性女聲-小萍':            self.vcn = "aisxping"        elif self.tk_cb_vcn.get() == '可愛童聲-許小寶':            self.vcn = "aisbabyxu"        elif self.tk_cb_vcn.get() == '親切女聲-小婧':            self.vcn = "aisjinger"


          接下來我們來魔改訊飛自帶的Python demo;


          # -*- 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 websocketimport datetimeimport hashlibimport base64import hmacimport jsonfrom urllib.parse import urlencodeimport sslfrom wsgiref.handlers import format_date_timefrom datetime import datetimefrom time import mktimeimport _thread as threadimport osimport?wave
          STATUS_FIRST_FRAME = 0 # 第一幀的標識STATUS_CONTINUE_FRAME = 1 # 中間幀標識STATUS_LAST_FRAME?=?2??#?最后一幀的標識
          PCM_PATH = "./demo.pcm"

          class Ws_Param(object): # 初始化 def __init__(self): self.tts_vcn = "" self.tts_business_args = "" self.tts_common_args = "" self.tts_text_data = "" self.APPID = "" self.APIKey = ""????????self.APISecret?=?""
          def set_tts_params(self, text, vcn): self.tts_vcn = vcn # 業(yè)務參數(shù)(business),更多個性化參數(shù)可在官網(wǎng)查看 self.tts_business_args = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": self.tts_vcn, "tte": "utf8"} # 使用小語種須使用以下方式,此處的unicode指的是 utf16小端的編碼方式,即"UTF-16LE"” # self.tts_text_data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")} self.tts_text_data = {"status": 2, "text": str(base64.b64encode(text.encode('utf-8')), "UTF8")}
          def set_params(self, appid, api_seccret, api_key): if appid != "": self.APPID = appid # 公共參數(shù)(common) self.tts_common_args = {"app_id": self.APPID}
          if api_key != "": self.APIKey = api_key
          if api_seccret != "": self.APISecret = api_seccret # 生成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" # 進行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') # 將請求的鑒權參數(shù)組合為字典 v = { "authorization": authorization, "date": date, "host": "ws-api.xfyun.cn" }
          ????????url?=?url?+?'?'?+?urlencode(v)
          return url

          def on_message(ws, message): try: message = json.loads(message) 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: err_msg = message["message"] print("sid:%s call error:%s code is:%s" % (sid, err_msg, 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.tts_common_args, "business": wsParam.tts_business_args, "data": wsParam.tts_text_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 text2wav(appid, api_secret, api_key, text, vcn, fname): wsParam.set_params(appid, api_secret, api_key) wsParam.set_tts_params(text, vcn) websocket.enableTrace(False) ws_url = wsParam.create_url() ws = websocket.WebSocketApp(ws_url, 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()

          # 注意一下需要填入自己的appid、api_secret、api_keyif __name__ == "__main__": text2wav(appid='xxx', api_secret='xxx', api_key='xxx', text="這是一個測試", vcn="xiaoyan", fname="./demo.wav")


          代碼寫好了,我們把Python代碼run起來,最終一個語音合成系統(tǒng)就這樣實現(xiàn)了!效果可以參考下圖:



          當前,各種云計算、云服務迅速發(fā)展,各大公司提供了豐富的資源,大大降低了人工智能開發(fā)的門檻,不需要懂語音合成的原理,只需不到半天時間,竟然可以這么快速開發(fā)出一個語音合成工具出來!


          你還有什么想要補充的嗎?

          免責聲明:本文內(nèi)容來源于網(wǎng)絡,文章版權歸原作者所有,意在傳播相關技術知識&行業(yè)趨勢,供大家學習交流,若涉及作品版權問題,請聯(lián)系刪除或授權事宜。



          瀏覽 56
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  中国一区二区毛片 | 蜜桃视频在线观看91 | 青娱乐免费视频一二三 | 777偷窥盗摄00000 | 免费做爱视频动漫 |