将Word、PDF、TXT等文档转换为MP3音频文件,让用户可以"听"文档内容,缓解视觉疲劳。
首次使用前,安装必要的依赖库:
python scripts/install_dependencies.py
或手动安装:
pip install docx2txt pdfplumber PyPDF2 pyttsx3 gtts
# 基本用法
python scripts/doc_to_speech.py 文档.docx
# 指定输出路径
python scripts/doc_to_speech.py 文档.docx -o 输出.mp3
# 调整语速
python scripts/doc_to_speech.py 文档.pdf -r 120
# 使用Google TTS(在线,质量更好)
python scripts/doc_to_speech.py 文档.txt -e gtts
# 转换多个文件
python scripts/doc_to_speech.py 文件1.docx 文件2.pdf 文件3.txt
# 转换整个文件夹
python scripts/doc_to_speech.py ./文档文件夹/ -o ./输出音频/
python scripts/doc_to_speech.py --list-voices
| 参数 | 说明 | 示例 |
|---|---|---|
| ------ | ------ | ------ |
input | 输入文件或文件夹路径 | 文档.docx |
-o, --output | 输出路径 | -o 音频.mp3 |
-e, --engine | TTS引擎 (pyttsx3 或 gtts) | -e pyttsx3 |
-v, --voice | 语音ID | -v 0 |
-r, --rate | 语速 (默认150) | -r 120 |
-l, --lang | 语言代码 (gtts用) | -l zh-cn |
--list-voices | 列出可用语音 | --list-voices |
当用户需要将文档转为语音时:
docx2txt 提取文本pdfplumber 或 PyPDF2 提取文本| 引擎 | 类型 | 优点 | 缺点 |
|---|---|---|---|
| ------ | ------ | ------ | ------ |
| pyttsx3 | 离线 | 无需网络,响应快,免费 | 语音质量一般 |
| gTTS | 在线 | 语音质量高,自然流畅 | 需要网络,有请求限制 |
python scripts/doc_to_speech.py 报告.docx -o 报告音频.mp3 -r 130
python scripts/doc_to_speech.py ./我的文档/ -o ./有声书/ -e gtts
from scripts.doc_to_speech import convert_file
# 转换单个文件
convert_file(
input_path="文章.pdf",
output_path="文章.mp3",
engine="pyttsx3",
rate=140
)
解决: 安装pdfplumber
pip install pdfplumber
解决:
-e gtts解决:
pyttsx3 代替 gtts解决: 调整语速参数 -r,建议范围 120-180
共 1 个版本