日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
利用Python打造一個語音合成系統(tǒng)

正文

大家好,我是Python人工智能技術(shù)

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都做網(wǎng)站、成都網(wǎng)站制作、嶧城網(wǎng)絡(luò)推廣、小程序開發(fā)、嶧城網(wǎng)絡(luò)營銷、嶧城企業(yè)策劃、嶧城品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學生創(chuàng)業(yè)者提供嶧城建站搭建服務(wù),24小時服務(wù)熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com

背景

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

語音合成系統(tǒng)

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

準備工作

首先我們電腦上需要安裝

  1. Anaconda
  2. Python 3.7
  3. visual studio code

步驟

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

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

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

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

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

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

  1. APPID
  2. APISecret
  3. APIKey

代碼實現(xià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):#進行語音合成

在這里,大家需要填上剛才從訊飛開放平臺控制臺獲取到的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è)置窗口是否可變,寬不可變,高可變,默認為True
self.lb=tk.Label(self.root,text='請選擇語音發(fā)音人')#標簽
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) #將當前選擇狀態(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='進行語音合成', 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()

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

# -*- 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 # 第一幀的標識
STATUS_CONTINUE_FRAME = 1 # 中間幀標識
STATUS_LAST_FRAME = 2 # 最后一幀的標識
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"
# 進行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')
# 將請求的鑒權(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)了。

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


本文名稱:利用Python打造一個語音合成系統(tǒng)
網(wǎng)站地址:http://www.5511xx.com/article/cciipcg.html