1、流程
1)换取token
用Api Key 和 SecretKey。访问https://openapi.baidu.com/oauth/2.0/token 换取 token
// appKey = Va5yQRHl********LT0vuXV4 // appSecret = 0rDSjzQ20XUj5i********PQSzr5pVw2 https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHl********LT0vuXV4&client_secret=0rDSjzQ20XUj5i********PQSzr5pVw2
返回
{ "access_token": "1.a6b7dbd428f731035f771b8d********.86400.1292922000-2346678-124328", "expires_in": 2592000, "refresh_token": "2.385d55f8615fdfd9edb7c4b********.604800.1293440400-2346678-124328", "scope": "public audio_tts_post ...", "session_key": "ANXxSNjwQDugf8615Onqeik********CdlLxn", "session_secret": "248APxvxjCZ0VEC********aK4oZExMB", }scope中含有audio_tts_post 表示有语音合成能力,没有该audio_tts_post 的token调用接口会返回502错误。 在结果中可以看见 token = 1.a6b7dbd428f731035f771b8d********.86400.1292922000-2346678-124328,在2592000秒(30天)后过期
2)访问合成接口
#从上文中我们获取的token是 1.a6b7dbd428f731035f771b8d********.86400.1292922000-2346678-124328 http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcdxxx&tok=1.a6b7dbd428f731035f771b8d****.86400.1292922000-2346678-124328&tex=%e7%99%be%e5%ba%a6%e4%bd%a0%e5%a5%bd&vol=9&per=0&spd=5&pit=5&aue=3 // 这是一个正常MP3的下载url // tex在实际开发过程中请urlencode2次"""
tex | 必填 | 合成的文本,使用UTF-8编码。小于2048个中文字或者英文数字。(文本在百度服务器内转换为GBK后,长度必须小于4096字节) |
tok | 必填 | 开放平台获取到的开发者access_token(见上面的“鉴权认证机制”段落) |
cuid | 必填 | 用户唯一标识,用来计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内 |
ctp | 必填 | 客户端类型选择,web端填写固定值1 |
lan | 必填 | 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh |
spd | 选填 | 语速,取值0-15,默认为5中语速 |
pit | 选填 | 音调,取值0-15,默认为5中语调 |
vol | 选填 | 音量,取值0-15,默认为5中音量 |
per | 选填 | 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声 |
aue | 选填 | 3为mp3格式(默认); 4为pcm-16k;5为pcm-8k;6为wav(内容同pcm-16k); 注意aue=4或者6是语音识别要求的格式,但是音频内容不是语音识别要求的自然人发音,所以识别效果会受影 |
- aue =3 ,返回为二进制mp3文件,具体header信息 Content-Type: audio/mp3;
- aue =4 ,返回为二进制pcm文件,具体header信息 Content-Type:audio/basic;codec=pcm;rate=16000;channel=1
- aue =5 ,返回为二进制pcm文件,具体header信息 Content-Type:audio/basic;codec=pcm;rate=8000;channel=1
- aue =6 ,返回为二进制wav文件,具体header信息 Content-Type: audio/wav;
"""
2、api 代码demo
# coding=utf-8 import sys import json IS_PY3 = sys.version_info.major == 3 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 API_KEY = ‘4E1BG9lTnlSeIf1NQFlrSq6h‘ SECRET_KEY = ‘544ca4657ba8002e3dea3ac2f5fdd241‘ TEXT = "欢迎使用百度语音合成。" # 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声 PER = 4 # 语速,取值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 = 3 FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"} FORMAT = FORMATS[AUE] CUID = "123456PYTHON" TTS_URL = ‘http://tsn.baidu.com/text2audio‘ class DemoError(Exception): pass """ TOKEN start """ TOKEN_URL = ‘http://openapi.baidu.com/oauth/2.0/token‘ SCOPE = ‘audio_tts_post‘ # 有此scope表示有tts能力,没有请在网页里勾选 def fetch_token(): print("fetch token begin") params = {‘grant_type‘: ‘client_credentials‘, ‘client_id‘: API_KEY, ‘client_secret‘: SECRET_KEY} post_data = urlencode(params) if (IS_PY3): post_data = post_data.encode(‘utf-8‘) req = Request(TOKEN_URL, post_data) try: f = urlopen(req, timeout=5) result_str = f.read() except URLError as err: print(‘token http response http code : ‘ + str(err.code)) result_str = err.read() if (IS_PY3): result_str = result_str.decode() print(result_str) result = json.loads(result_str) print(result) if (‘access_token‘ in result.keys() and ‘scope‘ in result.keys()): if not SCOPE in result[‘scope‘].split(‘ ‘): raise DemoError(‘scope is not correct‘) print(‘SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s‘ % (result[‘access_token‘], result[‘expires_in‘])) return result[‘access_token‘] else: raise DemoError(‘MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response‘) """ TOKEN end """ if __name__ == ‘__main__‘: token = fetch_token() tex = quote_plus(TEXT) # 此处TEXT需要两次urlencode print(tex) params = {‘tok‘: token, ‘tex‘: tex, ‘per‘: PER, ‘spd‘: SPD, ‘pit‘: PIT, ‘vol‘: VOL, ‘aue‘: AUE, ‘cuid‘: CUID, ‘lan‘: ‘zh‘, ‘ctp‘: 1} # lan ctp 固定参数 data = urlencode(params) print(‘test on Web Browser‘ + TTS_URL + ‘?‘ + data) 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(‘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)
3、sdk下载
pip install baidu-aip
5、sdk demo代码
# coding=utf-8 from aip import AipSpeech API_KEY = ‘DHEl3FqU9oxxx‘ # 替换成你的api_key 在创建的应用中查找 SECRET_KEY = ‘ZWGxEZjxxxxIMx7BeGnoW83u‘ # 替换成你的secret_key 在创建的应用中查找 APP_ID = ‘1xx3x3‘ # 替换成你的app_id client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) result = client.synthesis(u‘baidu是一家科技公司‘, ‘zh‘, 1, { ‘vol‘: 5, ‘per‘: 5, ‘spd‘: 4 }) # vol 控制音量 per 控制男女声 spd 控制速度 if not isinstance(result, dict): with open(‘auido.mp3‘, ‘wb‘) as f: f.write(result)
原文地址:https://www.cnblogs.com/kakawith/p/11005365.html
时间: 2024-11-07 22:05:23