form1.cn
Make a little progress every day

Python将一段文字转为MP3音频文件

13th of September 2022 Python Code 314

Python将一段文字转为MP3音频文件

# encoding=utf8

'''
Python将一段文字转为MP3音频文件
'''

# 导入包
import pyttsx3,librosa,os
from pydub import AudioSegment


# 定义方法
def txttomp3(text, savemp3):
	'''把文字转为mp3格式并保存文件'''
	engine = pyttsx3.init() 

	engine.setProperty('rate', 150) # 调整语速
	engine.setProperty('volume',1.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 = r"D:/test/test.wav"

	# 调用方法
	txttomp3(text, savemp3)