溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)

發(fā)布時(shí)間:2022-03-31 10:21:49 來(lái)源:億速云 閱讀:148 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

背景

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

語(yǔ)音合成系統(tǒng)

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

準(zhǔn)備工作

首先我們電腦上需要安裝

  • Anaconda

  • Python 3.7

  • visual studio code

步驟

這里我們選用訊飛開放平臺(tái)的WebAPI接口。

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

基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)

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

點(diǎn)擊左側(cè)的語(yǔ)音合成,再到下一級(jí)在線語(yǔ)音合成(流式版)

基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)

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

  • APPID

  • APISecret

  • APIKey

代碼實(shí)現(xiàn)

好了接下來(lái)進(jìn)行代碼實(shí)現(xiàn)了,首先安裝我們需要的兩個(gè)庫(kù)。

pip install websocket-client
pip install playsound

接下來(lái)我們定義一個(gè)類play,包含4個(gè)函數(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)行語(yǔ)音合成

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

def __init__(self):
        self.APP_ID = 'xxx'   #請(qǐng)?zhí)钌献约旱腶ppid
        self.API_KEY = 'xxx'  #請(qǐng)?zhí)钌献约旱腶ppkey
        self.SECRET_KEY = 'xxx' #請(qǐng)?zhí)钌献约旱腶ppsecret

        self.root=tk.Tk() #初始化窗口
        self.root.title("語(yǔ)音合成系統(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='請(qǐng)選擇語(yǔ)音發(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,也就是第一項(xiàng)
        self.cb.bind("<<ComboboxSelected>>", self.select_vcn)
        self.tk_tts_file=tk.Label(self.root,text='生成文件名')
        self.b1=tk.Button(self.root, text='進(jìn)行語(yǔ)音合成', width=10,height=1,command=self.xfyun_tts) #按鈕
        self.tk_play=tk.Button(self.root, text='播放', width=10,height=1,command=self.play_sound) #按鈕
        #各個(gè)組件的位置
        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è)置對(duì)應(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)

接下來(lái)我們來(lái)魔改訊飛自帶的Python demo為從而更加方便的來(lái)使用

# -*- coding:utf-8 -*-
#
#   author: iflytek
#
#  本demo測(cè)試時(shí)運(yùn)行的環(huán)境為:Windows + Python3.7
#  本demo測(cè)試成功運(yùn)行時(shí)所安裝的第三方庫(kù)及其版本如下:
#   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
#   合成小語(yǔ)種需要傳輸小語(yǔ)種文本、使用小語(yǔ)種發(fā)音人vcn、tte=unicode以及修改文本編碼方式
#  錯(cuò)誤碼鏈接:https://www.xfyun.cn/document/error-code (code返回錯(cuò)誤碼時(shí)必看)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
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)識(shí)
STATUS_CONTINUE_FRAME = 1  # 中間幀標(biāo)識(shí)
STATUS_LAST_FRAME = 2  # 最后一幀的標(biāo)識(shí)

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),更多個(gè)性化參數(shù)可在官網(wǎng)查看
                self.BusinessArgs = {"bgs":1,"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": self.vcn, "tte": "utf8"}
            #使用小語(yǔ)種須使用以下方式,此處的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格式的時(shí)間戳
        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')
        # 將請(qǐng)求的鑒權(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錯(cuò)誤的處理
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()

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

基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)

關(guān)于“基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“基于Python怎么編寫一個(gè)語(yǔ)音合成系統(tǒng)”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI