0 环境

WIn Xp,Python2.7,另外网络正常即可

1 注册用户

我已经注册过了,百度云盘的账号也可以用。

2 创建一个应用

点击创建应用

任意填写应用名称和应用描述。

得到这里的AppID、API_KEY和SECRET_KEY。在以下的小程序中需要用到。

3 pip安装SDK

windows下在cmd中输入:

python -m pip install baidu-aip

3 语音合成

百度语音的新手指南就是语音合成。初次体验还好。

新建一个main.py,添加以下代码。注意的是,API_KEY和SECRET_KEY需要改为自己的。这里API_KEY是我的KEY,SECRET_KEY我不能透露,读者需要修改为自己的SECRET_KEY。

# 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 = 'c0f0LBT3Bz9eulv8efGziCZH'

# 替换你的 SECRET_KEY
SECRET_KEY = '******'

# 大姚的订单信息内容文本
TEXT = "三分钟前,由北京市顺义区二经路与二纬路交汇处北侧,北京首都国际机场T3航站楼 去往 东城区北三环东路36号喜来登大酒店(北京金隅店)"



TTS_URL = 'http://tsn.baidu.com/text2audio'

"""  TOKEN start """

TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'


"""
    获取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, '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

    save_file = "error.txt" if has_error else u'大姚的订单信息.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("tts api  error:" + result_str)

    print("file saved as : " + save_file)

运行完成后会在本文件的同一个目录内生成一个音频文件,名为《大姚的订单信息.mp3》。 

4 语音识别

python2.7安装完成并配置好路径后,在命令行输入

python -m pip install baidu-aip

新建一个main1.py,添加以下代码。跟上面类似,API_KEY和SECRET_KEY需要改为自己的。这里API_KEY是我的KEY。读者需要修改为自己的API_KEY和SECRET_KEY。

# coding=utf-8


from aip import AipSpeech

""" 你的 APPID AK SK """
APP_ID = '16125607'
API_KEY = 'c0f0LBT3Bz9eulv8efGziCZH'
SECRET_KEY = '******'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 读取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

# 识别本地文件
result=client.asr(get_file_content('16k.pcm'), 'pcm', 16000, {
    'dev_pid': 1536,
})

print str(result).decode('unicode_escape')  

由于我并没有录制音频,音频样本在这里下载:

http://speech-doc.gz.bcebos.com/rest-api-asr/public_audio/16k.pcm

运行结果:

 

参考资料:
1 QuickStart语音合成:http://ai.baidu.com/docs#/QuickStart-TTS/top

2 语音识别PythonSDK:http://ai.baidu.com/docs#/ASR-Online-Python-SDK/top

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐