Python使用pyttsx3库实现文本转语音的完整教程
从安装到实战,一篇搞定!支持中英文,附完整代码示例
pyttsx3 是什么
pyttsx3 是 Python 最流行的 离线文本转语音(TTS)库。
核心特点
| 特性 | 说明 |
|---|---|
| 离线运行 | 无需联网,无需API |
| 支持中文 | 完美支持中英文 |
| 跨平台 | Windows / Mac / Linux |
| 速度快 | 实时语音合成 |
| 可定制 | 语速、音量、语音均可调 |
安装步骤
方式1:pip 安装(推荐)
# 基础安装 pip install pyttsx3 # Windows 用户额外安装(必须!) pip install pypiwin32 # 如果遇到版本问题,使用稳定版 pip install pyttsx3==2.90
方式2:虚拟环境安装(最佳实践)
# 创建虚拟环境 python -m venv tts_env # 激活环境 # Windows: tts_env\Scripts\activate # Mac/Linux: source tts_env/bin/activate # 安装 pip install pyttsx3 pypiwin32
验证安装
import pyttsx3 print(pyttsx3.__version__) # 应输出 2.90 或更高
快速开始(3行代码)
import pyttsx3
engine = pyttsx3.init()
engine.say("Hello, 我是Python!")
engine.runAndWait()
运行后,你的电脑就会说话了! 🎉
核心参数详解
参数1:调整音量(0.0 ~ 1.0)
import pyttsx3
engine = pyttsx3.init()
# 查看当前音量
volume = engine.getProperty('volume')
print(f"当前音量: {volume}") # 默认 1.0
# 设置音量(0.0 = 静音,1.0 = 最大)
engine.setProperty('volume', 0.5) # 50% 音量
engine.say("这是半音量的语音")
engine.runAndWait()
| 音量值 | 效果 |
|---|---|
| 0.0 | 🔇 静音 |
| 0.3 | 🔉 小声 |
| 0.7 | 🔊 正常 |
| 1.0 | 📢 最大 |
参数2:调整语速(50 ~ 300)
import pyttsx3
engine = pyttsx3.init()
# 查看当前语速
rate = engine.getProperty('rate')
print(f"当前语速: {rate}") # 默认 200
# 设置语速
engine.setProperty('rate', 150) # 变慢
engine.say("这是慢速语音")
engine.runAndWait()
engine.setProperty('rate', 250) # 变快
engine.say("这是快速语音")
engine.runAndWait()
| 语速值 | 效果 |
|---|---|
| 50 | 🐢 极慢(像树懒) |
| 150 | 🚶 慢速(适合教学) |
| 200 | 🏃 默认(正常说话) |
| 300 | 🚀 极快(像松鼠) |
参数3:切换语音(中英文)
import pyttsx3
engine = pyttsx3.init()
# 查看所有可用语音
voices = engine.getProperty('voices')
for i, voice in enumerate(voices):
print(f"[{i}] {voice.name}")
print(f" ID: {voice.id}\n")
# 切换到中文语音(通常索引为 1)
engine.setProperty('voice', voices[1].id)
engine.say("你好,这是中文语音")
engine.runAndWait()
# 切换到英文语音(通常索引为 0)
engine.setProperty('voice', voices[0].id)
engine.say("Hello, this is English")
engine.runAndWait()
输出示例(Windows):
[0] Microsoft David
ID: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
[1] Microsoft Huihui
ID: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH-CN_HUIHUI_11.0
进阶功能
功能1:保存为音频文件
import pyttsx3
engine = pyttsx3.init()
# 保存为 MP3 文件
engine.save_to_file("你好,这是保存的音频", "output.mp3")
engine.runAndWait()
print("✅ 音频已保存到 output.mp3")
功能2:暂停和继续
import pyttsx3
engine = pyttsx3.init()
engine.say("这是第一句")
engine.runAndWait()
engine.say("这是第二句")
engine.runAndWait()
# 暂停
engine.stop()
# 继续(需要重新初始化)
engine = pyttsx3.init()
engine.say("这是第三句")
engine.runAndWait()
功能3:批量朗读文本
import pyttsx3
def read_text(text, lang='cn'):
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id if lang == 'cn' else voices[0].id)
engine.setProperty('rate', 150)
engine.say(text)
engine.runAndWait()
# 批量朗读
texts = [
"第一句:Python真好用",
"第二句:文本转语音太酷了",
"第三句:Hello World"
]
for text in texts:
read_text(text)
完整实战案例
案例1:智能语音助手类
import pyttsx3
class VoiceAssistant:
def __init__(self):
self.engine = pyttsx3.init()
self.voices = self.engine.getProperty('voices')
def speak(self, text, lang='cn', rate=150, volume=0.8):
"""通用朗读方法"""
# 设置语音
voice_id = self.voices[1].id if lang == 'cn' else self.voices[0].id
self.engine.setProperty('voice', voice_id)
# 设置参数
self.engine.setProperty('rate', rate)
self.engine.setProperty('volume', volume)
# 朗读
self.engine.say(text)
self.engine.runAndWait()
def speak_cn(self, text):
"""中文朗读"""
self.speak(text, lang='cn')
def speak_en(self, text):
"""英文朗读"""
self.speak(text, lang='en')
def save_audio(self, text, filename):
"""保存音频"""
self.engine.save_to_file(text, filename)
self.engine.runAndWait()
# 🚀 使用示例
assistant = VoiceAssistant()
assistant.speak_cn("你好,我是你的智能语音助手!")
assistant.speak_en("Hello, I am your voice assistant!")
assistant.save_audio("测试保存", "test.mp3")
案例2:阅读器(朗读文本文件)
import pyttsx3
def read_file(filepath, lang='cn'):
"""朗读文本文件"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
text = f.read()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
voice_id = voices[1].id if lang == 'cn' else voices[0].id
engine.setProperty('voice', voice_id)
engine.setProperty('rate', 150)
engine.say(text)
engine.runAndWait()
print(f"✅ 已朗读文件: {filepath}")
except FileNotFoundError:
print(f"❌ 文件不存在: {filepath}")
# 使用
read_file("article.txt", lang='cn')
案例3:语音闹钟
import pyttsx3
import time
def voice_alarm(hour, minute, message):
"""语音闹钟"""
engine = pyttsx3.init()
engine.setProperty('rate', 180)
engine.setProperty('volume', 1.0)
while True:
now = time.localtime()
if now.tm_hour == hour and now.tm_min == minute:
engine.say(f"闹钟响了!{message}")
engine.runAndWait()
break
time.sleep(30) # 每30秒检查一次
# 设置早上7:30的闹钟
voice_alarm(7, 30, "起床啦!新的一天开始了!")
常见错误及解决方案
错误1:SyntaxError: invalid syntax(海象运算符)
原因:Python 版本 < 3.8
解决:
pip install pyttsx3==2.90
错误2:_ctypes.COMError: (-2147200966, ...)
原因:找不到可用语音
解决:
import pyttsx3
engine = pyttsx3.init()
# 🔑 关键:手动设置语音
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
engine.say("测试成功")
engine.runAndWait()
错误3:KeyError: None
原因:驱动初始化失败
解决:
pip uninstall pyttsx3 -y pip install pyttsx3==2.90 pip install pypiwin32
错误4:没有中文语音
解决:
Win + I→ 时间和语言 → 语音- 点击 “添加语音”
- 搜索 “Chinese” 并安装
- 重启电脑
总结速查表
| 操作 | 代码 |
|---|---|
| 初始化 | engine = pyttsx3.init() |
| 说话 | engine.say("文本") |
| 执行 | engine.runAndWait() |
| 语速 | engine.setProperty('rate', 150) |
| 音量 | engine.setProperty('volume', 0.8) |
| 切换语音 | engine.setProperty('voice', voices[0].id) |
| 保存文件 | engine.save_to_file("文本", "file.mp3") |
| 查看语音 | voices = engine.getProperty('voices') |
延伸推荐
| 库 | 特点 | 适用场景 |
|---|---|---|
| pyttsx3 | 离线、可定制 | 桌面应用、嵌入式 |
| gTTS | 联网、音质好 | 在线服务、API |
| edge-tts | 微软语音、自然 | 高质量语音生成 |
| pyttsx4 | pyttsx3 升级版 | 未来替代方案 |
到此这篇关于Python使用pyttsx3库实现文本转语音的完整教程的文章就介绍到这了,更多相关Python pyttsx3文本转语音内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python之tkinter进度条Progressbar用法解读
这篇文章主要介绍了Python之tkinter进度条Progressbar用法解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-05-05
Python数据可视化 pyecharts实现各种统计图表过程详解
这篇文章主要介绍了Python数据可视化 pyecharts实现各种统计图表过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-08-08
python GUI库图形界面开发之PyQt5中QWebEngineView内嵌网页与Python的数据交互传参详细方法
这篇文章主要介绍了python GUI库图形界面开发之PyQt中QWebEngineView内嵌网页与Python的数据交互详细方法实例,需要的朋友可以参考下2020-02-02


最新评论