百度的TTS API


TTS
代碼是百度給的樣例
修改TEXT,API_KEY和SECRET_KEY
按注釋修改參數
很好使

# 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 = '自己申請去'

SECRET_KEY = '自己申請去'



TEXT = "圖片中的花朵是:  玫 瑰 花"



# 發音人選擇, 基礎音庫:0為度小美,1為度小宇,3為度逍遙,4為度丫丫,

# 精品音庫:5為度小嬌,103為度米朵,106為度博文,110為度小童,111為度小萌,默認為度小美 

PER = 0

# 語速,取值0-15,默認為5中語速

SPD = 4

# 音調,取值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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM