You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacOS Sonoma下VSCode运行pyttsx3出现Runtime Error的解决方法

语音自动化代码运行报错:NameError: name 'objc' is not defined

问题描述

  • 设备:M1 MacBook
  • 系统:MacOS Sonoma 14.0
  • VSCode版本:1.84.2
  • Python版本:3.12
  • 依赖版本:pyttsx3 2.90、pyobjc 10.0
  • 问题:运行语音自动化代码时触发NameError: name 'objc' is not defined错误

代码示例

import webbrowser
import speech_recognition as sr
import pyttsx3

# 监听语音输入
def listen(language="en-IN"):
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)

    try:
        print("Recognizing...")
        # 根据选择的语言识别语音
        if language == "en-IN":
            query = recognizer.recognize_google(audio, language="en-IN")
        else:
            query = recognizer.recognize_google(audio, language="hi-IN")
        
        print(f"You said: {query}")
        return query.lower()
    except sr.UnknownValueError:
        print("Sorry, I didn't catch that. Can you repeat?")
        return ""
    except sr.RequestError:
        print("Sorry, there was an error processing the request.")
        return ""

# 文本转语音
def speak(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

if __name__ == "__main__":
    # 初始化助手并提示指令
    speak("Hello! I'm friday.How can I help you?")
    language = "en-IN"  # 默认使用英语

    # 持续监听指令并响应
    while True:
        command = listen(language)

        if "switch language" in command:
            # 切换英语/印地语
            if language == "en-IN":
                language = "hi-IN"
                speak("Switching to Hindi.")
            else:
                language = "en-IN"
                speak("Switching to English.")

        elif "open youtube" in command:
            # 打开YouTube
            speak("Opening YouTube...")
            webbrowser.open("https://www.youtube.com")
            
        elif "bye" in command:
            # 退出程序
            speak("Goodbye!")
            break
        
        else:
            # 未识别指令时提示重复
            speak("I didn't understand that command. Can you please repeat?")

报错信息

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pyttsx3/__init__.py", line 20, in init
    eng = _activeEngines[driverName]
          ~~~~~~~~~~~~~~^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/weakref.py", line 136, in __getitem__
    o = self.data[key]()
        ~~~~~~~~~^^^^^
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/Desktop/friday_trial /friday_code.py", line 38, in <module>
    speak("Hello! I'm your voice assistant. How can I help you?")
  File "/Users/Desktop/friday_trial /friday_code.py", line 32, in speak
    engine = pyttsx3.init()
             ^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pyttsx3/__init__.py", line 22, in init
    eng = Engine(driverName, debug)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pyttsx3/engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pyttsx3/driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1381, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1354, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1325, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 929, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 994, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pyttsx3/drivers/nsss.py", line 12, in <module>
    class NSSpeechDriver(NSObject):
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pyttsx3/drivers/nsss.py", line 13, in NSSpeechDriver
    @objc.python_method
     ^^^^
NameError: name 'objc' is not defined. Did you mean: 'object'?

原因分析

这不是代码或系统问题,是依赖版本兼容性问题:
pyttsx3 2.90版本的MacOS驱动(nsss.py)未适配pyobjc 10.0与Python 3.12,代码中直接使用objc模块但未正确导入,导致报错。

修复方案

方案1:降级pyobjc到兼容版本

卸载当前pyobjc,安装与pyttsx3 2.90、Python3.12兼容的版本:

pip uninstall pyobjc -y && pip install pyobjc==9.0.1

方案2:替换为兼容的TTS库

使用pyttsx4(pyttsx3的维护分支,支持更新的Python版本):

  1. 安装pyttsx4:
pip install pyttsx4
  1. 修改代码中的导入语句:
# 替换原有的 import pyttsx3
import pyttsx4 as pyttsx3

其余代码无需改动,直接运行即可。

方案3:手动修复pyttsx3驱动文件(不推荐)

找到pyttsx3安装目录下的nsss.py文件(路径参考报错信息中的位置),在文件开头添加:

import objc

该方法会在依赖更新后失效,不建议长期使用。


内容的提问来源于stack exchange,提问作者MoonWolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:04:51