先安装 pyttsx3
# encoding=utf8
'''
python将一段文字转为mp3音频文件
'''
import pyttsx3
# 实现方法:
def txttomp3(text, savemp3):
'''把文字为mp3格式并保存文件'''
engine = pyttsx3.init();
engine.setProperty('rate', 150) # 调整语速
engine.setProperty('volume', 2.0) # 调整音量
voices = engine.getProperty('voices');
engine.setProperty('voice', voices[0].id);
#engine.say(text);
engine.save_to_file(text, savemp3);
engine.runAndWait(); # 播放音频
print("转换成功!" + savemp3);
if __name__ == '__main__':
# 要转为MP3的文字
text = "获得一只企鹅(属性≈冠军剑士)"
# 保存MP3的目录路径
savemp3 = "./mp3/audio.mp3"
# 调用方法
txttomp3(text, savemp3)