发布于2026-07-01 阅读(0)
扫一扫,手机访问
从安装到实战,一篇搞定!支持中英文,附完整代码示例

一句话总结:pyttsx3 是 Python 生态里最受欢迎的 离线文本转语音(TTS)库。不用联网、不用申请任何 API,装好就能让电脑开口说话,而且中英文都支持,Windows、Mac、Linux 通吃。
看看它的核心特点,你就知道为什么这么多人选它了:
| 特性 | 说明 |
|---|---|
| 离线运行 | 无需联网,无需API |
| 支持中文 | 完美支持中英文 |
| 跨平台 | Windows / Mac / Linux |
| 速度快 | 实时语音合成 |
| 可定制 | 语速、音量、语音均可调 |
# 基础安装 pip install pyttsx3 # Windows 用户额外安装(必须!) pip install pypiwin32 # 如果遇到版本问题,使用稳定版 pip install pyttsx3==2.90
# 创建虚拟环境 python -m venv tts_env # 激活环境 # Windows: tts_envScriptsactivate # 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()
运行后,你的电脑就会说话了! ? 是不是很酷?
知道了怎么让它说话,接下来就是调教它——让声音更顺耳。核心参数其实就三个:音量、语速、语音。一个个来看。
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 | ? 最大 |
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 | ? 极快(像松鼠) |
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 Da vid
ID: HKEY_LOCAL_MACHINESOFTWAREMicrosoftSpeechVoicesTokensTTS_MS_EN-US_DA VID_11.0
[1] Microsoft Huihui
ID: HKEY_LOCAL_MACHINESOFTWAREMicrosoftSpeechVoicesTokensTTS_MS_ZH-CN_HUIHUI_11.0
注意:如果你发现没有中文语音,别急——后面常见错误部分有解决方案。
光能说话还不够?那就来点高级操作:把语音保存成文件、实现暂停续播、批量朗读……统统安排上。
import pyttsx3
engine = pyttsx3.init()
# 保存为 MP3 文件
engine.sa ve_to_file("你好,这是保存的音频", "output.mp3")
engine.runAndWait()
print("✅ 音频已保存到 output.mp3")
import pyttsx3
engine = pyttsx3.init()
engine.say("这是第一句")
engine.runAndWait()
engine.say("这是第二句")
engine.runAndWait()
# 暂停
engine.stop()
# 继续(需要重新初始化)
engine = pyttsx3.init()
engine.say("这是第三句")
engine.runAndWait()
需要说明的是:pyttsx3 的暂停/继续能力比较有限,实际使用中更常见的策略是分段朗读。
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)
理论知识够了?直接上三个真实场景的完整代码,copy 过去就能用。
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 sa ve_audio(self, text, filename):
"""保存音频"""
self.engine.sa ve_to_file(text, filename)
self.engine.runAndWait()
# ? 使用示例
assistant = VoiceAssistant()
assistant.speak_cn("你好,我是你的智能语音助手!")
assistant.speak_en("Hello, I am your voice assistant!")
assistant.sa ve_audio("测试保存", "test.mp3")
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')
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, "起床啦!新的一天开始了!")
新手最容易踩的坑,这里一次性列出来,省得你到处搜。
原因:Python 版本 < 3.8
解决:
pip install pyttsx3==2.90
原因:找不到可用语音
解决:
import pyttsx3
engine = pyttsx3.init()
# ? 关键:手动设置语音
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
engine.say("测试成功")
engine.runAndWait()
原因:驱动初始化失败
解决:
pip uninstall pyttsx3 -y pip install pyttsx3==2.90 pip install pypiwin32
解决:
Win + I → 时间和语言 → 语音最后一张表,把最常用的操作整理好了,以后直接拿来用。
| 操作 | 代码 |
|---|---|
| 初始化 | engine = pyttsx3.init() |
| 说话 | engine.say("文本") |
| 执行 | engine.runAndWait() |
| 语速 | engine.setProperty('rate', 150) |
| 音量 | engine.setProperty('volume', 0.8) |
| 切换语音 | engine.setProperty('voice', voices[0].id) |
| 保存文件 | engine.sa ve_to_file("文本", "file.mp3") |
| 查看语音 | voices = engine.getProperty('voices') |
如果 pyttsx3 满足不了你,还有这些库可以试试,各有千秋:
| 库 | 特点 | 适用场景 |
|---|---|---|
| pyttsx3 | 离线、可定制 | 桌面应用、嵌入式 |
| gTTS | 联网、音质好 | 在线服务、API |
| edge-tts | 微软语音、自然 | 高质量语音生成 |
| pyttsx4 | pyttsx3 升级版 | 未来替代方案 |
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8