惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News | PayPal Newsroom
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
C
Cisco Blogs
SecWiki News
SecWiki News
Know Your Adversary
Know Your Adversary
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
NISL@THU
NISL@THU
WordPress大学
WordPress大学
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Threat Research - Cisco Blogs
AI
AI
Simon Willison's Weblog
Simon Willison's Weblog
Security Archives - TechRepublic
Security Archives - TechRepublic
有赞技术团队
有赞技术团队
L
LINUX DO - 热门话题
Hacker News: Ask HN
Hacker News: Ask HN
V
V2EX
G
GRAHAM CLULEY
TaoSecurity Blog
TaoSecurity Blog
Hugging Face - Blog
Hugging Face - Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Fortinet All Blogs
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
云风的 BLOG
云风的 BLOG
Recorded Future
Recorded Future
Latest news
Latest news
The Hacker News
The Hacker News
aimingoo的专栏
aimingoo的专栏
T
Troy Hunt's Blog
S
Schneier on Security
I
Intezer
Google DeepMind News
Google DeepMind News
A
Arctic Wolf
Apple Machine Learning Research
Apple Machine Learning Research
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threatpost
爱范儿
爱范儿
The Register - Security
The Register - Security
S
SegmentFault 最新的问题
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
宝玉的分享
宝玉的分享
Recent Commits to openclaw:main
Recent Commits to openclaw:main
美团技术团队
B
Blog RSS Feed

博客园 - jack_Meng

WinForm 双屏开发中屏幕适配与窗口定位 高考志愿填报之计算机类专业院校报考指南(2026版) WebSocket 快速入门教程(附示例源码) 自动生成项目工具--AutoBuilder,一键干掉80%的重复CRUD工作 C#/.NET/.NET Core优秀项目和框架2026年5月简报 在Win10系统中,默认使用照片查看器 C#实现控制台多区域输出 解决: 您的连接不是私密连接,您目前无法访问 因为此网站使用了 HSTS 小说下载 网页版时间,可全屏显示 个人笔记本连接公共WIFI的安全措施 追更 HelloGitHub 一整年,年度盘点 基于Rust开发的m3u8下载器M3U8Quicker:支持断点续传、边下边播 新写了个直播录制工具,可录制抖音快手斗鱼直播 bing 每日一图 --- 桌面壁纸 一款基于 C# 开发的 Windows 10/11 系统增强优化工具 适合个人的免费域名 语雀里存了三年的笔记,导出到了本地插件----YuqueOut C# 也能像 Python 一样写脚本 | .NET 10 构建基于文件的应用 js 双击页面 开始/暂停 页面滚动 使用bat批量给txt追加内容 Python摄像头监控:运动检测+自动录像+时间水印 【译】告别繁琐查错:认识下新的 Visual Studio Debugger Agent Workflow 好消息,在 Visual Studio 中可以免费使用 GitHub Copilot 了! [C#] 零依赖高性能跨平台 Web 胶水库 -- PicoServer 我的第一款独立产品--TaskManager 写 EF Core 查询,优化查询语句 最新.NET新手入门学习网站合集(2026更新版) Avalonia UI:.NET 跨平台桌面开发的“真香”选择
一个 txt 生成并保存 mp3的 Python 脚本
jack_Meng · 2026-04-18 · via 博客园 - jack_Meng

你要我给你做一个一键朗读整个文件夹所有 TXT 并保存 MP3的 Python 脚本吗?

下面给你一个一键朗读文件夹里所有 TXT、自动生成 MP3的 Python 脚本,用的是微软 Edge 语音(音色超自然、免费、无次数限制)。

支持:

  • 指定一个文件夹,自动扫描所有 .txt
  • 每个 txt 生成一个同名 MP3
  • 中文完美、女声 / 男声可换
  • 不乱码、支持长文本

1. 先安装依赖

打开 CMD / 终端运行:


2. 完整脚本(直接用)

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))

3. 怎么用

  1. TXT_FOLDER 改成你放 txt 的文件夹路径

    • Windows 示例:r"C:\Users\Tom\Desktop\小说"
    • Mac 示例:"/Users/Tom/Desktop/txt"
  2. 运行脚本

  3. 每个 txt 旁边会自动生成 同名 MP3


4. 可选声音(直接替换 VOICE 即可)

zh-CN-XiaoxiaoNeural   # 晓晓(标准女声,推荐)
zh-CN-YunxiNeural      # 云希(男声)
zh-CN-YunyangNeural    # 云扬(成熟男声)
zh-CN-XiaochenNeural   # 晓辰(女声)
zh-CN-YunjianNeural    # 云健(男声)

出处:豆包生成

=================================================

个人使用

版本1

优化:增加了计数功能,程序运行时提示输入文件夹路径

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

版本2

优化:增加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