前言
因爲該功能的實現,需要使用百度的語音合成技術,所以,首先需要註冊並登陸百度AI:
https://ai.baidu.com/tech/speech
創建應用
點擊創建應用,創建自己的應用。
按照提示填入相應內容就好。
獲取應用的API Key和Secret Key
編寫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 = 'nu9r2plGFi3s1ugayDPSM6Mk'
SECRET_KEY = 'G62YGnq84eKTqu0mBgvdpmC6gNBzHdai'
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)
替換API Key和Secret Key
將上面代碼中的API_KEY 和SECRET_KEY,替換成自己應用中的API Key和Secret Key,運行代碼。
生成的音頻文件
生成的音頻文件名爲:大姚的訂單信息.mp3。打開MP3聽到的聲音就是上面輸入的文字。
TEXT = "三分鐘前,由北京市順義區二經路與二緯路交匯處北側,北京首都國際機場T3航站樓 去往 東城區北三環東路36號喜來登大酒店(北京金隅店)"
上面的文字可以替換成想自己想要轉語音的其他文字。