語(yǔ)音合成-百度

代碼地址:https://github.com/Baidu-AIP/speech-demo/blob/master/rest-api-tts/python/tts.py

# coding=utf-8
import sys
import json

#判斷是否是py3版本,默認(rèn)py3
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 
    #將字典里面所有的鍵值轉(zhuǎn)化為query-string格式(key=value&key=value),并且將中文轉(zhuǎn)碼
    from urllib.parse import quote_plus 
    #可編碼斜線"/" 這個(gè)主要是根據(jù)api url要求格式
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 = '4E1BG9lTnlSeIf1NQFlrSq6h'
SECRET_KEY = '544ca4657ba8002e3dea3ac2f5fdd241'
#上面的碼需要自己申請(qǐng)生成

TEXT = "歡迎使用百度語(yǔ)音合成。"
#TEXT可以封裝起來

# 發(fā)音人選擇, 0為普通女聲,1為普通男生,3為情感合成-度逍遙,4為情感合成-度丫丫,默認(rèn)為普通女聲
PER = 4
# 語(yǔ)速,取值0-15,默認(rèn)為5中語(yǔ)速
SPD = 5
# 音調(diào),取值0-15,默認(rèn)為5中語(yǔ)調(diào)
PIT = 5
# 音量,取值0-9,默認(rèn)為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] #選取MP3的格式

CUID = "123456PYTHON" 
#用戶唯一標(biāo)識(shí),用來區(qū)分用戶,填寫機(jī)器 MAC 地址或 IMEI 碼,長(zhǎng)度為60以內(nèi)

TTS_URL = 'http://tsn.baidu.com/text2audio'
#語(yǔ)音合成api的地址

class DemoError(Exception):
    pass


"""  TOKEN start """

TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力,沒有請(qǐng)?jiān)诰W(wǎng)頁(yè)里勾選

#獲取token,從而啟動(dòng)應(yīng)用
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 固定參數(shù)

    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)

應(yīng)用版本:

from aip import AipSpeech

""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
#在上面代碼中,常量APP_ID在百度云控制臺(tái)中創(chuàng)建,常量API_KEY與
#SECRET_KEY是在創(chuàng)建完畢應(yīng)用后,系統(tǒng)分配給用戶的,均為字符串,
#用于標(biāo)識(shí)用戶,為訪問做簽名驗(yàn)證,可在AI服務(wù)控制臺(tái)中的應(yīng)用列表中查看。
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

result  = client.synthesis('你好百度', 'zh', 1, {
    'vol': 5,
})
#這樣我們就獲得了 result

#保存result,或者彈出錯(cuò)誤信息
if not isinstance(result, dict):
    with open('auido.mp3', 'wb') as f:
        f.write(result)

代碼地址:https://blog.csdn.net/u011519550/article/details/84981585

//獲取mp3文件的時(shí)間長(zhǎng)度
from mutagen.mp3 import MP3
audio = MP3("/home/wangjinyu/Desktop/Linkin Park - Iridescent.mp3")
print(audio.info.length)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容