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

推荐订阅源

Google DeepMind News
Google DeepMind News
C
Check Point Blog
J
Java Code Geeks
腾讯CDC
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
罗磊的独立博客
Last Week in AI
Last Week in AI
B
Blog
IT之家
IT之家
S
SegmentFault 最新的问题
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
博客园 - 聂微东
U
Unit 42
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
MyScale Blog
MyScale Blog

博客园 - jack_Meng

2026年AI编程工具大全,33个主流工具 .NET 异常处理的"暗门":代码里被 catch 吃掉的异常,你依然能抓住它——FirstChanceException Visual Studio 插件 Gittoy , 我做了一个 vs 版的 gittoolbox 用 C 语言实现任务栏图标动画,支持使用表情包gif/webp 如何用0预算推广项目 开源的 Windows 桌面整理工具 被罚了500后,整个人都变老实了 提取网页表格,一键导出 CSV:一个 Bookmarklet 脚本就够了 从零搭建一个最小 AI Agent:Python 完整示例 + AI调用机制详解 CASIO卡西欧计算器的自检模式——2种自检方式 C#把字符串按每两个字符一组,组之间加空格 C#程序从指定路径或网络加载引用的DLL 设置程序PrivatePath,配置引用程序集的指定路径(分离exe和dll) .NET/WPF 程序密钥加密存储:使用 DPAPI 实现安全兼容 一线大厂的Git规范 一线大厂的数据库规范 Python自动化实战:常用的类库和使用场景 工控生态之展示与交互:怎么让工业软件不再"丑" 一个 Python 项目带你入门AI应用开发课程介绍----系列文章 开源好用的酷狗音乐播放器:VibeMusic PowerShell + C# 实现桌面文字提醒,类似于“激活Windows”的功能 【Python】2026动态文字壁纸,一键让你的桌面加上动态效果 Python 用 tkinter 实现在 Windows 上提示文本消息的实现(模拟安卓手机上的 Toast 效果) 用Python在Windows桌面弹出文字提示 在Windows桌面背景上添加自定义文字 常用AI提示词汇总 chrome浏览器,Google新标签页添加快捷图标 油候脚本中,使用GM_info对象,打印脚本信息 使用油候脚本,移除页面无法选择文字 高中免费电子教辅资料合集
一个 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