登录百度智能云:百度智能云-智能时代基础设施
搜索短文本在线合成
进入后点击立即使用
创建应用
根据个人需要填写相关内容即可
之后便可在管理应用界面看见自己创建的应用
请记录下API Key和Secret Key
编写如下py代码
# coding=utf-8
import sys
import json
import os
import pygame
import time
# 保证兼容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
# 替换你的 API_KEY
API_KEY = '*************'
# 替换你的 SECRET_KEY
SECRET_KEY = '*************'
TEXT = ""
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__':
# 读文件
with open('设置一个自己需要读取文本的路径') as f:
TEXT = f.read()
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)
# 采用pygame后台播放mp3文件
pygame.mixer.init()
track = pygame.mixer.music.load('传入语音的位置\语音.mp3')
pygame.mixer.music.play()
time.sleep(10)
pygame.mixer.music.stop()
vue将需要朗读内容ID传到后台我在SpringBoot中继承Mybatis所以通过ID查询对应的内容并将内容输出到txt文本中再调用python程序生成语音播放
// 写入文件
File file = new File("路径*********");
try {
FileOutputStream outputStream = new FileOutputStream(file);
byte content[] = trends_content.getBytes();
try {
outputStream.write(content);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 调用py
Process proc;
try {
proc = Runtime.getRuntime().exec("python py文件路径");// 执行py文件
} catch (IOException e) {
e.printStackTrace();
}
至此完成文本生成语音并播报
小白入门、能力有限、以此记录。