以下代码只要输入自己在百度语音开放平台创建应用后获得的 API Key和Secret Key 即可使用
# coding=utf-8
import sys
import json
IS_PY3 = sys.version_info.major == 3 #判断Python的版本号
if IS_PY3:
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
else:
import urllib2
from urllib import quote_plus
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import URLError
from urllib import urlencode
TEXT = "天行健,君子以自强不息";
# 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声
PER = 0
# 语速,取值0-15,默认为5中语速
SPD = 5
# 音调,取值0-15,默认为5中语调
PIT = 5
# 音量,取值0-9,默认为5中音量
VOL = 5
# 下载的文件格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
AUE = 6
FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"}
FORMAT = FORMATS[AUE]
CUID = "123456PYTHON"
class DemoError(Exception):
pass
SCOPE = 'audio_tts_post' # 有此scope表示有tts能力,没有请在网页里勾选
def fetch_token():
API_KEY = "自己获得"
SECRET_KEY = "自己获得"
TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token' #获取令牌的网址
params = {'grant_type': 'client_credentials',
'client_id': API_KEY,
'client_secret': SECRET_KEY} # 需要提交的参数
post_data = urlencode(params).encode("utf-8")
req = Request(TOKEN_URL, post_data) # 转换网址及参数格式
try:
f = urlopen(req, timeout=5)
result_str = f.read().decode()#接受返回来的信息
except URLError as err:
print('token http response http code : ' + str(err.code))
result_str = err.read()
result = json.loads(result_str) #将信息转换成字典类型,便于查找令牌
if ('access_token' in result.keys() and 'scope' in result.keys()):
if not SCOPE in result['scope'].split(' '):
raise DemoError('scope is not correct')
return result['access_token']#返回令牌,以便进行语音合成
def get_yuyin():
TTS_URL = 'http://tsn.baidu.com/text2audio'
token = fetch_token()
tex = quote_plus(TEXT) # 此处TEXT需要两次urlencode
params = {'tok': token,
'tex': tex,#合成的文本
'per': PER,#发音人选择
'spd': SPD,#语速
'pit': PIT,#音调
'vol': VOL,#音量
'aue': AUE,#合成语音的格式
'cuid': CUID,#用户唯一标识
'lan': 'zh',#固定值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()
except URLError as err:
print('asr http response http code : ' + str(err.code))
result_str = err.read()
has_error = True
save_file = "error.txt" if has_error else 'result.' + FORMAT
with open(save_file, 'wb') as of:
of.write(result_str)
if has_error:
if (IS_PY3):
result_str = str(result_str, 'utf-8')
print("tts api error:" + result_str)
print("result saved as :" + save_file)
if __name__ == '__main__':
get_yuyin()
781



被折叠的 条评论
为什么被折叠?



