python文本转语音

文本转语音

使用语音合成模块实现把文字转化为语音播报(纯python代码)
相当于把.txt 转化为.mp3
# coding=utf-8
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
import requests


def get_access_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    data = {
        'grant_type': 'client_credentials',  # 固定值
        'client_id': 'g75f8mPozZ8w*****ZixaYOk',  # 在开放平台注册后所建应用的API Key
        'client_secret': 'NA112mGW65k*****EUK6wFpX95bMQxft'  # 所建应用的Secret Key
    }
    res = requests.post(url, data=data)
    res = res.json()
    access_token = res['access_token']
    print(access_token)
    return access_token


def compound_tts(tts_url, text):
    token = get_access_token()
    tex = quote_plus(text)
    params = {'tok': token, 'tex': tex, '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.reason))
        result_str = err.reason()
        has_error = True

    save_file = "error.txt" if has_error else u'想听吗.mp3'
    with open(save_file, 'wb') as f:
        f.write(result_str)

    if has_error:
        result_str = str(result_str, 'utf-8')
        print("语音api发生错误:" + result_str)

    print("生成成功 : " + save_file)


if __name__ == '__main__':
    tts_url = 'http://tsn.baidu.com/text2audio'
    text = "我们家宇哥说了,你再哔哔揍你"
    compound_tts(tts_url, text)

😃😃😃 客官点个赞再走 😃😃😉

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值