
2024年您產(chǎn)品必備的10大AI API推薦
app_id = '應(yīng)用 ID'
api_key = 'API 開(kāi)發(fā)密鑰'
secret_key = '密鑰'
AipSpeech(app_id, api_key, secret_key).main()
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ō)明
?。
為了方便使用,我們可對(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ǔ)音合成
?獲取完整源碼。
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ō)
2024年您產(chǎn)品必備的10大AI API推薦
GraphRAG:基于PolarDB+通義千問(wèn)api+LangChain的知識(shí)圖譜定制實(shí)踐
使用Node.js、Express和MySQL構(gòu)建REST API
天氣API推薦:精準(zhǔn)獲取氣象數(shù)據(jù)的首選
基于自定義數(shù)據(jù)集的微調(diào):Alpaca與LLaMA模型的訓(xùn)練
OAuth和OpenID Connect圖解指南
有哪些新聞媒體提供Open API?
現(xiàn)在做大模型,還有靠譜且免費(fèi)的API接口嗎?
如何運(yùn)用AI提高自己的工作效率?
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)