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

推荐订阅源

人人都是产品经理
人人都是产品经理
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
Recorded Future
Recorded Future
N
News and Events Feed by Topic
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
博客园 - 叶小钗
B
Blog
Vercel News
Vercel News
T
Tenable Blog
T
The Exploit Database - CXSecurity.com
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
F
Fortinet All Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Microsoft Security Blog
Microsoft Security Blog
S
Securelist
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Palo Alto Networks Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
DataBreaches.Net
Cyberwarzone
Cyberwarzone
Engineering at Meta
Engineering at Meta
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Check Point Blog
A
About on SuperTechFans
W
WeLiveSecurity
The GitHub Blog
The GitHub Blog

博客园 - 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 跨平台桌面开发的“真香”选择 开源可商用 .NET Office 转 PDF 工具/库 - MiniPdf c# 常用且免费的 AI 编程工具 CodeGeeX,在vs 2019中使用的 AI 大模型工具 支持在 vs studio 2019中安装的 免费的 AI 辅助工具 .Net Framework 使用Lazy<T>延迟初始化对象 微软官网wpf例程源码下载地址 GitHub“神级”项目学习网址 开源协议介绍 Windows 窗体控件和等效的 WPF 控件 sql server backup database 爬取七猫中文网小说 ASP.NET Core 内存缓存实战 CliWrap —— .NET 最优雅的命令行交互库 .NET 高级开发 | 设计、实现一个事件总线框架 一个基于 .NET Core + Vue3 构建的开源全栈平台 Admin 系统 C#/.NET/.NET Core优秀项目和框架2026年3月简报--工作流引擎 C# 如何减少代码运行时间:7 个实战优化技巧
一个 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