文本转mp3

def text_to_mp3(text):
"""
文本转mp3

参数:
text (str): 要转换的文字

返回:
str: mp3文件路径
"""
output_file = None
# 内部定义异步函数
async def _amain():
nonlocal output_file
VOICE = "zh-CN-YunxiNeural" # zh-CN-YunxiNeural zh-CN-XiaoxiaoNeural
RATE = "+30%" # 调整语速
communicate = edge_tts.Communicate(text, VOICE, rate=RATE)
# 输出文件名 %Y%m%d_%H%M%S
file_path = datetime.datetime.now().strftime("%m%d_%H%M%S") + ".mp3"
output_file = save_path + file_path
try:
with open(output_file, "wb") as file:
async for chunk in communicate.stream():
if chunk["type"] == "audio":
file.write(chunk["data"])
elif chunk["type"] == "WordBoundary":
# print(f"WordBoundary: {chunk}")
pass
# 确保文件已正确创建并且有内容
if Path(output_file).stat().st_size > 0:
return return_dict(200, "转换成功", {"mp3_path": file_path})
else:
return return_dict(400, "mp3文件为空")
except Exception as e:
return return_dict(400, f"报错信息:{e}")

# 使用 asyncio.run 来运行异步函数,对外表现为同步调用
return asyncio.run(_amain())