app_id = '應(yīng)用 ID'
api_key = 'API 開(kāi)發(fā)密鑰'
secret_key = '密鑰'
AipSpeech(app_id, api_key, secret_key).main()

3.實(shí)現(xiàn)流程

3.1 準(zhǔn)備工作

1、進(jìn)入百度云官網(wǎng) https://cloud.baidu.com/,并注冊(cè)、登陸。

2、進(jìn)入控制臺(tái)頁(yè)面,選擇語(yǔ)音技術(shù),并點(diǎn)擊?創(chuàng)建應(yīng)用

3、填寫(xiě)相關(guān)信息后點(diǎn)擊,立即創(chuàng)建

4、創(chuàng)建完畢后,就可管理剛剛創(chuàng)建的應(yīng)用,查看?應(yīng)用ID、密鑰?等參數(shù)。

5、進(jìn)入?SDK?資源網(wǎng)頁(yè),下載在線合成?Python-SDK?壓縮文件。

6、解壓后的 SDK 中的 api 目錄結(jié)構(gòu)如下圖,具體實(shí)現(xiàn)可參考?接口說(shuō)明?。

3.2 API 封裝、改寫(xiě)

為了方便使用,我們可對(duì) SDK 進(jìn)行封裝,改寫(xiě)部分內(nèi)容。

1、新建?baidu_speech_synthesis.py?文件。

# -*- coding: utf-8 -*-

"""
Speech_Synthesis
"""

import base64
import hmac
import json
import hashlib
import datetime
import time
import sys
import requests

2、將?base.py?文件中?AipBase?類的相關(guān)代碼拷貝到剛剛創(chuàng)建的?baidu_speech_synthesis.py?文件中,刪除?python2?的相關(guān)寫(xiě)法。

# 以上略
class AipBase(object):
"""
AipBase
"""
__accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token'
__reportUrl = 'https://aip.baidubce.com/rpc/2.0/feedback/v1/report'
__scope = 'brain_all_scope'

def __init__(self, app_id, api_key, secret_key):
"""
AipBase(app_id, api_key, secret_key)
"""
self._app_id = app_id.strip()
self._api_key = api_key.strip()
self._secret_key = secret_key.strip()
self._auth_obj = {}
self._is_cloud_user = None
self.__client = requests
self.__connect_timeout = 60.0
self.__socket_timeout = 60.0
self._proxies = {}
self.__version = '2_0_0'

def get_version(self):
"""
version
"""
return self.__version

def set_connection_timeout_in_millis(self, ms):
"""
set_connection_timeout_in_millis
建立連接的超時(shí)時(shí)間(單位:毫秒)
"""
self.__connect_timeout = ms / 1000.0

def set_socket_timeout_in_millis(self, ms):
"""
set_socket_timeout_in_millis
通過(guò)打開(kāi)的連接傳輸數(shù)據(jù)的超時(shí)時(shí)間(單位:毫秒)
"""
self.__socket_timeout = ms / 1000.0

def set_proxies(self, proxies):
"""
proxies
"""
self._proxies = proxies
# 由于代碼量大,以下略...

3、將?speech.py?文件中?AipSpeech?類的相關(guān)代碼拷貝到剛剛創(chuàng)建的?baidu_speech_synthesis.py?文件中。

# 以上略
class AipSpeech(AipBase):
"""
Aip Speech
"""
__asrUrl = 'http://vop.baidu.com/server_api'
__ttsUrl = 'http://tsn.baidu.com/text2audio'

def _is_permission(self, auth_obj):
"""
check whether permission
"""
return True

def _proccess_request(self, url, params, data, headers):
"""
參數(shù)處理
"""
token = params.get('access_token', '')
if not data.get('cuid', ''):
data['cuid'] = hashlib.md5(token.encode()).hexdigest()
if url == self.__asrUrl:
data['token'] = token
data = json.dumps(data)
else:
data['tok'] = token
if 'access_token' in params:
del params['access_token']
return data

def _proccess_result(self, content):
"""
formate result
"""
try:
return super(AipSpeech, self)._process_result(content)
except Exception as e:
return {
'__json_decode_error': content,
}
# 由于代碼量大,以下略...

4、處理baidu_speech_synthesis.py?文件中?disable_warnings()?的導(dǎo)包問(wèn)題,改寫(xiě)部分方法,修改部分變量命名。

from urllib3 import disable_warnings
from urllib.parse import urlencode
from urllib.parse import quote
from urllib.parse import urlparse

disable_warnings()

5、接口相關(guān)參數(shù)配置如下圖。

6、在 AipSpeech 中封裝 main 入口方法,我配置 per 為 3 ,選擇男生情感合成。

class AipSpeech(AipBase):
"""
Aip Speech
"""
# 中間部分略
def main(self):
"""入口方法"""
api_ = AipSpeech(self._app_id, self._api_key, self._secret_key)
# 我們要合成文本信息保存在 baidu_speech.txt 文件中
with open("baidu_speech.txt", 'r', encoding="utf-8") as read_f:
read_content = read_f.read()
result = api_.synthesis(read_content, 'zh', 1, {'vol': 5, 'per': 3})
# 識(shí)別正確返回二進(jìn)制數(shù)據(jù) 錯(cuò)誤則返回dict碼
if not isinstance(result, dict):
# 合成的語(yǔ)音文件名為
with open('baidu_speech.mp3', 'wb') as f:
f.write(result)

以上,便完成了整個(gè)百度語(yǔ)音合成的 API 封裝,關(guān)注公眾號(hào),后臺(tái)回復(fù)?語(yǔ)音合成?獲取完整源碼。

4.使用 API 實(shí)現(xiàn)語(yǔ)音合成

1、配置 API 參數(shù),在 baidu_speech_synthesis.py 最下方定義 API 調(diào)用 demo。

if __name__ == '__main__':
app_id = '這里改成你的應(yīng)用 ID'
api_key = '這里改成你的API 開(kāi)發(fā)密鑰'
secret_key = '這里改成你密鑰'
AipSpeech(app_id, api_key, secret_key).main()

2、baidu_speech.txt 文件內(nèi)容如下圖(這里使用相見(jiàn)恨晚的歌詞測(cè)試):

3、執(zhí)行完程序,會(huì)在同級(jí)目錄下生成一個(gè)名為 baidu_speech.mp3 的音頻文件,下面我可以使用播放工具播放即可。

5.總結(jié)

1、原創(chuàng)文章已全部更新至 Github:https://github.com/kelepython/kelepython

2、本文永久博客地址:https://kelepython.readthedocs.io/zh/latest/c03/c03_02.html

3、整個(gè)實(shí)現(xiàn)案例比較簡(jiǎn)單,建議大家親自嘗試一下。

4、封裝代碼時(shí)一定要細(xì)心,建議每次封裝完一個(gè)小塊,就執(zhí)行驗(yàn)證其正確性。

5、案例合成語(yǔ)音使用中音量、情感合成男聲、普通男聲、普通女聲,如果感興趣,可自行調(diào)整參數(shù)嘗試。

6、關(guān)注公眾號(hào),后臺(tái)回復(fù)?語(yǔ)音合成?獲取完整源碼,有任何疑問(wèn)歡迎留言交流。

文章轉(zhuǎn)自微信公眾號(hào)@可樂(lè)python說(shuō)

上一篇:

利用Django和Kimi大模型開(kāi)發(fā)知識(shí)庫(kù)問(wèn)答系統(tǒng)的案例

下一篇:

如何用Power BI批量調(diào)用API數(shù)據(jù)?
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)