87 lines
2.6 KiB
Python
87 lines
2.6 KiB
Python
#coding=utf-8
|
||
|
||
'''
|
||
requires Python 3.6 or later
|
||
pip install requests
|
||
'''
|
||
import base64
|
||
import json
|
||
import uuid
|
||
import requests
|
||
|
||
from Config.Config import HS_APP_ID, HS_ACCESS_TOKEN, HS_CLUSTER_ID, HS_VOICE_TYPE
|
||
|
||
appid = HS_APP_ID
|
||
access_token= HS_ACCESS_TOKEN
|
||
cluster = HS_CLUSTER_ID
|
||
|
||
voice_type = HS_VOICE_TYPE
|
||
host = "openspeech.bytedance.com"
|
||
api_url = f"https://{host}/api/v1/tts"
|
||
|
||
header = {"Authorization": f"Bearer;{access_token}"}
|
||
|
||
request_json = {
|
||
"app": {
|
||
"appid": appid,
|
||
"token": "access_token",
|
||
"cluster": cluster
|
||
},
|
||
"user": {
|
||
"uid": "388808087185088"
|
||
},
|
||
"audio": {
|
||
"voice_type": voice_type,
|
||
"encoding": "mp3",
|
||
"speed_ratio": 1.0,
|
||
"volume_ratio": 1.0,
|
||
"pitch_ratio": 1.0,
|
||
},
|
||
"request": {
|
||
"reqid": str(uuid.uuid4()),
|
||
"text": "我是小何啊,这是什么鬼~",
|
||
"text_type": "plain",
|
||
"operation": "query",
|
||
"with_frontend": 1,
|
||
"frontend_type": "unitTson"
|
||
|
||
}
|
||
}
|
||
|
||
if __name__ == '__main__':
|
||
try:
|
||
resp = requests.post(api_url, json=request_json, headers=header)
|
||
print(f"resp body: {resp.json()}")
|
||
|
||
# 检查响应状态
|
||
if resp.status_code == 200:
|
||
resp_data = resp.json()
|
||
if resp_data.get("code") == 3000 and "data" in resp_data:
|
||
data = resp_data["data"]
|
||
|
||
# 检查data是否为空
|
||
if data:
|
||
try:
|
||
# 解码Base64数据
|
||
audio_data = base64.b64decode(data)
|
||
|
||
# 保存为MP3文件
|
||
output_file = "test_tts_output.mp3"
|
||
with open(output_file, "wb") as f:
|
||
f.write(audio_data)
|
||
print(f"音频文件已成功保存为: {output_file}")
|
||
except Exception as decode_error:
|
||
print(f"Base64解码或文件保存失败: {str(decode_error)}")
|
||
# 打印数据前100个字符,以便调试
|
||
print(f"数据前100个字符: {data[:100]}")
|
||
else:
|
||
print("错误: 返回的data字段为空")
|
||
else:
|
||
print(f"API返回错误: code={resp_data.get('code')}, message={resp_data.get('message')}")
|
||
else:
|
||
print(f"HTTP请求失败: 状态码={resp.status_code}")
|
||
except Exception as e:
|
||
print(f"发生异常: {str(e)}")
|
||
import traceback
|
||
traceback.print_exc()
|