吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 4554|回复: 6
收起左侧

[Python 转载] 基于百度API将文字转成语音

[复制链接]
mygaryge 发表于 2022-4-27 10:50
本帖最后由 mygaryge 于 2022-4-27 11:14 编辑

第一次发帖希望大家多鼓励!
基于百度API和Python实现简单的文字转语音

首先注册和登陆百度语音
免费领取资源
image.png
创建应用
image.png

记下自己的 APIkey和 Secret Key写入代码对应的位置
image.png


代码如下:
[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)



运行后会生成一个时间名称的 MP3,相关的参数我已经在代码里写了注释,需要的话加入到代码91行 的 params里就可以了


如果报以下错误信息是因为百度申请的资源还没下来,或者你还没有申请免费资源。
{"err_detail":"16: Open api characters limit reached","err_msg":"16: Open api characters limit reached","err_no":502,"err_subcode":16,"tts_logid":3405513447}

有问题留言或私信的可以一起研究。

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

MasterChen 发表于 2022-4-27 15:34
Thank you,This is a great share
Sen 发表于 2022-4-27 16:39
Terrorist 发表于 2022-4-27 16:48
let me see; thank you for sharing!  Welcome to exchange and sharing!!
hlq0514 发表于 2022-5-4 09:22
谢谢分享
chinguy 发表于 2022-5-5 08:15
这个还是蛮好用的,不过现在转语音的软件也是蛮多的。
 楼主| mygaryge 发表于 2022-5-5 08:19
chinguy 发表于 2022-5-5 08:15
这个还是蛮好用的,不过现在转语音的软件也是蛮多的。

谢谢,主要是自己研究用,多一种选择总是好的
lenvon2012 发表于 2023-11-11 12:08
谢谢分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-23 17:10

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表