


























你要我给你做一个一键朗读整个文件夹所有 TXT 并保存 MP3的 Python 脚本吗?
下面给你一个一键朗读文件夹里所有 TXT、自动生成 MP3的 Python 脚本,用的是微软 Edge 语音(音色超自然、免费、无次数限制)。
支持:
.txt打开 CMD / 终端运行:
import asyncio
import edge_tts
import os
from pathlib import Path
# ===================== 配置区 =====================
# 你的 TXT 文件夹路径
TXT_FOLDER = r"C:\Users\你的名字\Desktop\txt文件夹"
# 声音选择(下面有更多可选)
VOICE = "zh-CN-XiaoxiaoNeural" # 晓晓女声
# VOICE = "zh-CN-YunxiNeural" # 云希男声
# ==================================================
async def text_to_speech(txt_path, mp3_path):
try:
with open(txt_path, "r", encoding="utf-8") as f:
text = f.read()
communicate = edge_tts.Communicate(text, VOICE)
await communicate.save(mp3_path)
print(f"✅ 已生成:{mp3_path}")
except Exception as e:
print(f"❌ 失败:{txt_path},原因:{str(e)}")
async def batch_read_all_txt(folder):
folder = Path(folder)
txt_files = list(folder.glob("*.txt"))
if not txt_files:
print("文件夹里没有找到 txt 文件")
return
print(f"共找到 {len(txt_files)} 个 txt,开始朗读生成 MP3...\n")
for txt in txt_files:
mp3 = txt.with_suffix(".mp3")
await text_to_speech(txt, mp3)
print("\n🎉 全部完成!")
if __name__ == "__main__":
asyncio.run(batch_read_all_txt(TXT_FOLDER))
把 TXT_FOLDER 改成你放 txt 的文件夹路径
r"C:\Users\Tom\Desktop\小说""/Users/Tom/Desktop/txt"运行脚本
每个 txt 旁边会自动生成 同名 MP3
zh-CN-XiaoxiaoNeural # 晓晓(标准女声,推荐)
zh-CN-YunxiNeural # 云希(男声)
zh-CN-YunyangNeural # 云扬(成熟男声)
zh-CN-XiaochenNeural # 晓辰(女声)
zh-CN-YunjianNeural # 云健(男声)
出处:豆包生成
=================================================
优化:增加了计数功能,程序运行时提示输入文件夹路径

import asyncio import edge_tts from pathlib import Path # ===================== 配置区 ===================== # 声音选择 VOICE = "zh-CN-XiaoxiaoNeural" # 晓晓女声 # VOICE = "zh-CN-YunxiNeural" # 云希男声 # ================================================== async def text_to_speech(txt_path: Path, mp3_path: Path, index: int, total: int): try: text = txt_path.read_text(encoding="utf-8") if not text.strip(): print(f"⚠️ [{index}/{total}] 内容为空,跳过:{txt_path.name}") return communicate = edge_tts.Communicate(text, VOICE) await communicate.save(mp3_path) print(f"✅ [{index}/{total}] 已生成:{mp3_path}") except Exception as e: print(f"❌ [{index}/{total}] 失败:{txt_path.name},错误:{str(e)}") async def batch_read_all_txt(folder: str): folder = Path(folder) if not folder.exists(): print(f"❌ 文件夹不存在:{folder}") return txt_files = sorted(folder.glob("*.txt")) total = len(txt_files) if total == 0: print("📂 文件夹内没有找到 .txt 文件") return print(f"📚 共找到 {total} 个 txt 文件,开始生成语音...\n") for idx, txt_file in enumerate(txt_files, start=1): mp3_file = txt_file.with_suffix(".mp3") await text_to_speech(txt_file, mp3_file, idx, total) print("\n🎉 全部语音合成完成!") if __name__ == "__main__": # 让用户输入文件夹路径 txt_folder = input("请输入 TXT 文件夹路径:").strip().strip('"').strip("'") asyncio.run(batch_read_all_txt(txt_folder))
View Code
优化:增加mp3子目录,单独保存音频文件

import asyncio import edge_tts import datetime from pathlib import Path # ===================== 配置区 ===================== # 声音选择 VOICE = "zh-CN-XiaoxiaoNeural" # 晓晓女声 # VOICE = "zh-CN-YunxiNeural" # 云希男声 # ================================================== async def text_to_speech(txt_path: Path, mp3_path: Path, index: int, total: int): try: text = txt_path.read_text(encoding="utf-8") if not text.strip(): print(f"⚠️ [{index}/{total}] 内容为空,跳过:{txt_path.name}") return communicate = edge_tts.Communicate(text, VOICE) await communicate.save(mp3_path) print(f"✅ [{index}/{total}] 已生成:{mp3_path}") except Exception as e: print(f"❌ [{index}/{total}] 失败:{txt_path.name},错误:{str(e)}") async def batch_read_all_txt(folder: str): folder = Path(folder) if not folder.exists(): print(f"❌ 文件夹不存在:{folder}") return txt_files = sorted(folder.glob("*.txt")) total = len(txt_files) if total == 0: print("📂 文件夹内没有找到 .txt 文件") return print(f"📚 共找到 {total} 个 txt 文件,开始生成语音...\n") print(f"开始时间:[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]") for idx, txt_file in enumerate(txt_files, start=1): mp3_dir = txt_file.parent / "mp3" # 子目录名 mp3_dir.mkdir(exist_ok=True) # 自动创建 mp3_file = mp3_dir / txt_file.with_suffix(".mp3").name await text_to_speech(txt_file, mp3_file, idx, total) print("\n🎉 全部语音合成完成!") print(f"完成时间:[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]") if __name__ == "__main__": # 让用户输入文件夹路径 txt_folder = input("请输入 TXT 文件夹路径:").strip().strip('"').strip("'") asyncio.run(batch_read_all_txt(txt_folder))
View Code
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。