豆包语音合成文档入口:账号登录-火山引擎
#coding=utf-8
'''
requires Python 3.6 or later
pip install requests
'''
import base64
import json
import requests
from playsound import playsound
tts_file_name="doubaotts.mp3"
def doubao_tts(text):
'''语音合成'''
appid = "" #修改成自己的
access_token= "" #修改成自己
cluster = "volcano_tts"
voice_type = "zh_female_daimengchuanmei_moon_bigtts" #音色:呆萌川妹
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": "uid123"
},
"audio": {
"voice_type": voice_type,
"encoding": "mp3",
"compression_rate": 1,
"rate": 24000,
"speed_ratio": 1.0,
"volume_ratio": 1.0,
"pitch_ratio": 1.0,
"emotion": "happy",
"language": "cn"
},
"request": {
"reqid": "uuid",
"text": text,
"text_type": "plain",
"operation": "query",
"silence_duration": "125",
"with_frontend": "1",
"frontend_type": "unitTson",
"pure_english_opt": "1"
}
}
file_name= tts_file_name
try:
resp = requests.post(api_url, json.dumps(request_json), headers=header)
# print(f"resp body: \n{resp.json()}")
if "data" in resp.json():
data = resp.json()["data"]
file_to_save = open(file_name, "wb")
file_to_save.write(base64.b64decode(data))
return True
else:
return False
except Exception as ex:
# ex.with_traceback()
print(ex)
doubao_tts("通过本文,我们了解了如何在Python中通过pygame库播放MP3文件的基本方法")
playsound(f'D:/2025_work/project/ai_bot_project/{tts_file_name}')