试了几种简单的文本转语音的方法,效果一般合成痕迹明显,不过考虑到也没有用什么复杂的模型,要什么自行车。
写个博文记录下。用到了pyttsx3/pyttsx4、edge_tts、speech、win32com.client等方法,可调整的参数直接看代码里面的注释
import pyttsx3
#import pyttsx4 as pyttsx3 # 似乎和3没啥区别
import win32com.client as client # 和pyttsx3音色一样,也是windows自带的语音合成声音
import speech
import edge_tts
import gtts
import asyncio
# edge_tts 必须异步,且需要联网
async def edge_tts_fun(text : str, output : str, voice : str, rate : str, volume : str, pitch : str):
voice_list = ["zh-CN-shaanxi-XiaoniNeural", "zh-CN-YunjianNeural", "zh-CN-YunxiNeural", "zh-CN-YunxiaNeural", \
"zh-CN-YunyangNeural", "zh-CN-liaoning-XiaobeiNeural", "zh-CN-XiaoxiaoNeural", "zh-CN-XiaoyiNeural"]
if (voice not in voice_list):
print("voice invalid")
return
tts = edge_tts.Communicate(text, voice, rate=rate, volume=volume, pitch=pitch)
await tts.save(output)
return
# 依赖于windows自带的语音,部分音色需要修改注册表添加,可以调整的参数较少
def pyttsx3_fun(text, output,
rate : int = 100,
volume : float = 1.0):
engine = pyttsx3.init() # 初始化语音引擎
engine.setProperty('rate', rate) # 设置语速
engine.setProperty('volume',volume) # 设置音量
voices = engine.getProperty('voices')
print("voice info:\n" + str(voices[0]))
engine.setProperty('voice',voices[0].id) #设置第一个语音合成器, 其他的无法合成中文语音
engine.save_to_file(text, output)
engine.runAndWait()
return
# 和pyttsx3差不多,就不多看了
def win32com_fun(text, output):
fileStream = client.Dispatch("SAPI.SpFileStream")
fileStream.Open(output, 3, False)
spVoice = client.Dispatch("SAPI.SpVoice")
spVoice.AudioOutputStream = fileStream
spVoice.Speak(text)
fileStream.Close()
if __name__ =="__main__":
print("tts demo\n")
file_name = "text.txt"
file_content = ""
edge_tts_param = ['zh-CN-YunxiNeural', '+10%', '+0%', "+0Hz"] # 音色、语速、音量、频率(低沉/尖锐)
pyttsx3_param = [200, 1.0] # 语速,音量
with open(file_name, 'r', encoding = 'utf-8') as f:
file_content += str(f.read())
print(file_content)
#speech.say(file_content) # speech没有找到保存音频文件的接口
pyttsx3_fun(file_content, "Speak_by_pyttsx3.mp3", pyttsx3_param[0], pyttsx3_param[1])
asyncio.run(edge_tts_fun(file_content, "Speak_by_edge_tts.mp3", \
edge_tts_param[0], edge_tts_param[1], edge_tts_param[2], edge_tts_param[3]))
# win32com_fun(file_content, "Speak_by_win32com.mp3") # 和pyttsx3的效果一样
print("Done!")