py3调用讯飞tts,分享下。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
这是利用了 讯飞 的 在线文本转语音 api,把单句文本转为语音文件,并保存到本地。
需要先填入 APPID 和 API_KEY。
详情见 https://www.xfyun.cn/services/online_tts
'''
import json
import requests
import time
import hashlib
import base64
import os
URL = 'http://api.xfyun.cn/v1/service/v1/tts'
AUE = 'lame' # raw=wav, lame=mp3
APPID = ''
API_KEY = ''
def getHeader():
curTime = str(int(time.time())).encode('utf-8')
param = {
'aue': AUE,
'auf': 'audio/L16;rate=16000',
'voice_name': 'xiaoyan',
'engine_type': 'intp65',
}
paramBytes = str(param).encode('utf-8')
# fix format (if ' or space exists, returns params error.)
paramBytes = paramBytes.replace(b'\'', b'\"').replace(b' ', b'')
paramBase64 = base64.b64encode(paramBytes)
m2 = hashlib.md5()
m2.update(API_KEY.encode('utf-8') + curTime + paramBase64)
checkSum = m2.hexdigest()
header = {
'X-CurTime': curTime,
'X-Param': paramBase64,
'X-Appid': APPID,
'X-CheckSum': checkSum,
'X-Real-Ip': '127.0.0.1',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
}
return header
def xunfei_tts(text):
header = getHeader()
data = {'text': text}
r = requests.post(URL, headers=header, data=data)
if r.headers['Content-Type'] == "audio/mpeg":
print("success | sid: %s | %s" % (r.headers['sid'], text[:10]))
return r.content
else:
print(r.text)
if __name__ == '__main__':
text = '床前明月光,疑是地上霜。'
text += 'The moonlight flow on the floor, just like frost.'
result = xunfei_tts(text)
if result:
root = os.path.split(os.path.realpath(__file__))[0]
ext = '.wav'if AUE == "raw" else '.mp3'
file = os.path.join(root, 'test' + ext)
with open(file, 'wb') as f:
f.write(result)