Python使用pyttsx3库实现文本转语音的完整教程

 更新时间:2026年05月20日 08:16:49   作者:detayun  
本文详细介绍了Python文本转语音库pyttsx3的完整使用指南,主要内容包括pyttsx3的特点,安装方法,快速入门示例等内容,希望可以帮助开发者快速掌握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:没有中文语音

解决

  1. Win + I → 时间和语言 → 语音
  2. 点击 “添加语音”
  3. 搜索 “Chinese” 并安装
  4. 重启电脑

总结速查表

操作代码
初始化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微软语音、自然高质量语音生成
pyttsx4pyttsx3 升级版未来替代方案

到此这篇关于Python使用pyttsx3库实现文本转语音的完整教程的文章就介绍到这了,更多相关Python pyttsx3文本转语音内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论