Python调用腾讯API合成语音
腾讯语音合成
腾讯AI开放平台中有ai语音合成的接口,其体验网址是https://ai.qq.com/product/aaitts.shtml。
官网的介绍是这样的:腾讯语音合成依托腾讯领先的语音技术和深度学习算法,为开发者提供全面优质的文字转语音服务。支持中英双语及多种音色,合成语音自然流畅,近乎真人发声。可为智能助手、智能机器人、文学阅读等领域提供语音合成解决方案,让您的应用开口说话。
Python调用腾讯接口
官网的示例代码是PHP的:
// 设置请求数据
$appkey = 'a95eceb1ac8c24ee28b70f7dbba912bf';
$params = array(
'app_id' => '1000001',
'speaker' => '1',
'format' => '2',
'volume' => '0',
'speed' => '100',
'text' => '腾讯,你好',
'aht' => '0',
'apc' => '58',
'time_stamp' => strval(time()),
'nonce_str' => strval(rand()),
'sign' => '',
);
$params['sign'] = getReqSign($params, $appkey);
// 执行API调用
$url = 'https://api.ai.qq.com/fcgi-bin/aai/aai_tts';
$response = doHttpPost($url, $params);
echo $response;
我参考这个代码写了一份python的:
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 20:57:24 2019
@author: HUI
"""
import time
from os import path
from urllib.request import urlopen
from urllib.parse import urlencode
from urllib.parse import quote_plus
import hashlib
import random
import base64
#生成sign
def getReqSign(params,key):
dict_kl = sorted(params)
s = ''
for k in dict_kl:
v = params[k]
if v != '':
v0 = str(quote_plus(str(v)))
s = s + k + '=' + v0 + '&'
s = s + 'app_key=' + key;
m = hashlib.md5()
m.update(s.encode("utf8"))
sign = m.hexdigest()
sign = sign.upper()
print('sign:',sign)
return sign
appid = '1000001'
appkey = 'a95eceb1ac8c24ee28b70f7dbba912bf'
text = '腾讯ai语音合成'
url = 'https://api.ai.qq.com/fcgi-bin/aai/aai_tts'
time_s = int(time.time())
m = hashlib.md5()
m.update(str(time_s).encode("utf8"))
nonce_s = m.hexdigest()
nonce_s = nonce_s[0:random.randint(1,31)]
params ={'app_id':appid,
'speaker':'1',
'format':'2',
'volume': '0',
'speed':'100',
'text':text,
'aht':'0',
'apc':'58',
'time_stamp':time_s,
'nonce_str':nonce_s,
'sign':''
}
params['sign'] = getReqSign(params,appkey)
s = urlencode(params)
res = urlopen(url,s.encode()) #网络请求
res_str = res.read().decode()
res_dict = eval(res_str)
print('return result : ')
print('ret:',res_dict['ret'])
print('msg:',res_dict['msg'])
if res_dict['ret'] == 0:
res_data = res_dict['data']
res_data_format = res_data['format']
res_data_speech = res_data['speech']
res_data_md5sum = res_data['md5sum']
filepath = path.dirname(__file__) #目录
file = '/wav01.wav'
base64_data = res_data_speech
ori_image_data = base64.b64decode(base64_data)
fout = open(filepath+file, 'wb')
fout.write(ori_image_data)
fout.close()
print("output file '",filepath,file,"' success")
print('over')
说明
1.需要去官网https://ai.qq.com/创建应用,得到APPID和APPKEY,然后将代码中默认的appid = '1000001’和appkey = 'a95eceb1ac8c24ee28b70f7dbba912bf’替换一下。
2.text 是想要被转换成语音的文字,这个文字似乎不能太长,否则特别容易请求失败。
3. 如果一切正常,会在代码所在目录下新增一个wav格式的音频文件,这个就是返回的腾讯合成的音频。
4. 有时候会提示‘system busy, please try again later’,原因暂时不清楚。
作者:hui_0_
出处:https://blog.csdn.net/hui_0_/article/details/102675804