文本转语音
使用语音合成模块实现把文字转化为语音播报(纯python代码)
相当于把.txt 转化为.mp3
# coding=utf-8
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.parse import quote_plus
import requests
def get_access_token():
url = 'https://aip.baidubce.com/oauth/2.0/token'
data = {
'grant_type': 'client_credentials', # 固定值
'client_id': 'g75f8mPozZ8w*****ZixaYOk', # 在开放平台注册后所建应用的API Key
'client_secret': 'NA112mGW65k*****EUK6wFpX95bMQxft' # 所建应用的Secret Key
}
res = requests.post(url, data=data)
res = res.json()
access_token = res['access_token']
print(access_token)
return access_token
def compound_tts(tts_url, text):
token = get_access_token()
tex = quote_plus(text)
params = {'tok': token, 'tex': tex, 'cuid': "quickstart", 'lan': 'zh', 'ctp': 1} # lan ctp 固定参数
data = urlencode(params)
req = Request(tts_url, data.encode('utf-8'))
has_error = False
try:
f = urlopen(req)
result_str = f.read()
headers = dict((name.lower(), value) for name, value in f.headers.items())
has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)
except URLError as err:
print('http response http code :' + str(err.reason))
result_str = err.reason()
has_error = True
save_file = "error.txt" if has_error else u'想听吗.mp3'
with open(save_file, 'wb') as f:
f.write(result_str)
if has_error:
result_str = str(result_str, 'utf-8')
print("语音api发生错误:" + result_str)
print("生成成功 : " + save_file)
if __name__ == '__main__':
tts_url = 'http://tsn.baidu.com/text2audio'
text = "我们家宇哥说了,你再哔哔揍你"
compound_tts(tts_url, text)
😃😃😃 客官点个赞再走 😃😃😉