Edge-TTS是由微软推出的文本转语音Python库,通过微软Azure Cognitive Services转化文本为自然语音。可以作为付费文本转语音TTS服务的替代品,Edge-TTS支持40多种语言和300种声音,提供优质的语音输出 。 edge-tts支持英语、汉语、日语、韩语、法语等40多种语言,共300多种可选声音。
首先,通过Python包管理工具pip来安装Edge-TTS库。只需在命令行中输入以下命令:pip install edge-tts。
然后,可以通过cmd命令:edge-tts --list-voices 来查看所有的语音,其中美式英语的语音有:
Name: en-US-AnaNeural
Gender: Female
Name: en-US-AndrewMultilingualNeural
Gender: Male
Name: en-US-AndrewNeural
Gender: Male
Name: en-US-AriaNeural
Gender: Female
Name: en-US-AvaMultilingualNeural
Gender: Female
Name: en-US-AvaNeural
Gender: Female
Name: en-US-BrianMultilingualNeural
Gender: Male
Name: en-US-BrianNeural
Gender: Male
Name: en-US-ChristopherNeural
Gender: Male
Name: en-US-EmmaMultilingualNeural
Gender: Female
Name: en-US-EmmaNeural
Gender: Female
Name: en-US-EricNeural
Gender: Male
Name: en-US-GuyNeural
Gender: Male
Name: en-US-JennyNeural
Gender: Female
Name: en-US-MichelleNeural
Gender: Female
Name: en-US-RogerNeural
Gender: Male
Name: en-US-SteffanNeural
Gender: Male
下载英语电子书或者其他英语文本文档等资料,选好英语语音后,在deepseek中输入提示词:
你是一个Python编程专家,写一个tts文本转语音的Python脚本,具体步骤如下:
读取文件夹“F:\aivideo”里面的txt文本文档;
调用Edge-TTS库将txt文本转换成语音,语音格式为mp3,保存到同一个文件夹中,
具体参数:Gender为女性,Name为:en-US-AriaNeural,语速为:-30%;
注意:
每一步都要输出信息
使用 asyncio.run 来运行异步函数,自动管理事件循环的创建和关闭。
使用 chardet 库来检测Txt文件编码格式,然后使用对应的编码来读取文件;
Txt文件中可能包含非 UTF-8 编码的字符, 可以使用 errors='ignore' 参数来忽略这些错误字符。
源代码:
import os
import asyncio
import edge_tts
import sys
async def text_to_speech(text, output_file):
communicate = edge_tts.Communicate(text, "en-US-AriaNeural", rate="-30%")
await communicate.save(output_file)
def process_files(folder_path):
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
txt_file_path = os.path.join(folder_path, filename)
mp3_file_path = os.path.join(folder_path, os.path.splitext(filename)[0] + ".mp3")
print(f"Reading text from {txt_file_path}")
with open(txt_file_path, 'r', encoding='utf-8') as file:
text = file.read()
print(f"Converting text to speech and saving to {mp3_file_path}")
asyncio.run(text_to_speech(text, mp3_file_path))
print(f"Conversion complete for {txt_file_path}")
if __name__ == "__main__":
folder_path = r"F:\aivideo"
print(f"Processing files in {folder_path}")
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
process_files(folder_path)
print("All files processed.")