import http.client
import json
def post_request(appKey, token, text, voice, speech_rate, format, sampleRate):
host = 'nls-gateway-cn-shanghai.aliyuncs.com'
url = 'https://' + host + '/stream/v1/tts'
# 设置HTTPS Headers。
httpHeaders = {
'Content-Type': 'application/json'
}
# 设置HTTPS Body。
body = {'appkey': appKey, 'token': token, 'text': text, 'voice': voice, 'speech_rate': speech_rate,
'format': format, 'sample_rate': sampleRate}
body = json.dumps(body)
conn = http.client.HTTPSConnection(host)
conn.request(method='POST', url=url, body=body, headers=httpHeaders)
# 处理服务端返回的响应。
response = conn.getresponse()
contentType = response.getheader('Content-Type')
body = response.read()
# 将音频文件保存在桌面上的音频文件夹里
filename = rf'C:\Users\burn_\Desktop\音频\{text}.mp3'
if 'audio/mpeg' == contentType:
with open(filename, mode='wb') as f:
f.write(body)
else:
print('没有转换的文本:' + str(body))
conn.close()
appKey = 'appKey'
token = 'token'
# text = '要转化的文本'
# 音频格式
format = 'MP3'
sampleRate = 16000
# 语音人
voice = 'aiya'
# 语速,-500~200
speech_rate = '-200'
# 单文本转语音
# post_request(appKey, token, text, voice, speech_rate, format, sampleRate)
# 多文本转语音
with open("文本.txt", 'r', encoding='utf8') as f:
for i in f:
text = i.strip()
post_request(appKey, token, text, voice, speech_rate, format, sampleRate)
阿里云文本转语音python代码
于 2023-05-22 18:45:35 首次发布