欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」基于百度API文字转语音Python示例代码

作者 : 自学哈 本文共3503个字,预计阅读时间需要9分钟 2022-10-14 共170人阅读
也想出现在这里? 联系我们

准备工作

1、首先需要去百度智能云注册账号,官网:https://cloud.baidu.com/

2、登陆进入百度语音,领取免费资源

3、创建应用,记下自己的 APIkey和 Secret Key写入代码对应的位置

Python示例代码

# coding=utf-8
 
import sys
import json
 
# 保证兼容python2以及python3
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
API_KEY = '你的APIKEY'
 
# 替换你的 SECRET_KEY
SECRET_KEY = '你的Secret Key'
 
# 信息内容文本
TEXT = "这里填写你要转成语音的文字"
 
 
 
TTS_URL = 'http://tsn.baidu.com/text2audio'
 
"""  TOKEN start """
 
TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
# 发音人选择, 基础音库:0为度小美,1为度小宇,3为度逍遥,4为度丫丫,
# 精品音库:5为度小娇,103为度米朵,106为度博文,110为度小童,111为度小萌,默认为度小美 
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 = 3
 
"""
    获取token
"""
def fetch_token():
    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()
 
 
    result = json.loads(result_str)
 
    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not 'audio_tts_post' in result['scope'].split(' '):
            print ('please ensure has check the tts ability')
            exit()
        return result['access_token']
    else:
        print ('please overwrite the correct API_KEY and SECRET_KEY')
        exit()
 
 
"""  TOKEN end """
 
if __name__ == '__main__':
 
    token = fetch_token()
 
    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode
     
    params = {'tok': token, 'tex': tex, 'per':PER,'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.code))
        result_str = err.read()
        has_error = True
 
    import time
    localtime = time.localtime(time.time())
    time = str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())))
    save_file = "errorinfo.txt" if has_error else time+'.mp3'
 
    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("api error:" + result_str)
 
    print("file saved as : " + save_file)

相关专题

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」基于百度API文字转语音Python示例代码
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号