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

开发Python聊天机器人时调用sr.Microphone出现unexpected token错误的解决求助

解决"Microphone is an unexpected token"错误

嘿,这个问题很好解决!你碰到的错误完全是因为少加了一对括号导致的。

在你的代码里,这行错误的写法:

with sr.Microphone as source:

问题出在sr.Microphone上——它是speech_recognition库中的一个类,要创建它的实例来作为音频输入源,必须加上括号(),就像初始化其他Python类一样。少了括号的话,Python会把Microphone当成一个未被正确调用的类引用,自然会抛出"Microphone is an unexpected token"的错误。

给你修正后的完整核心代码:

import speech_recognition as sr
r = sr.Recognizer()
# 关键修正:给Microphone加上括号,创建实例
with sr.Microphone() as source: # use the default microphone as the audio source
    audio = r.listen(source) # listen for the first phrase and extract it into audio data
try:
    # 额外提醒:原代码的r.recognize()是错误的,正确调用谷歌识别的方法是recognize_google
    print("You said " + r.recognize_google(audio)) 
except LookupError: # speech is unintelligible
    print("Could not understand audio")

另外顺便提个小细节:原代码里的r.recognize(audio)其实是不正确的,speech_recognition库中调用谷歌语音识别服务的正确方法是r.recognize_google(audio),如果不改的话,运行时还会遇到"AttributeError"的错误哦~

要是之后运行时碰到麦克风无法识别的情况,可以试试指定设备索引,比如sr.Microphone(device_index=0),你可以先调用sr.Microphone.list_microphone_names()来查看系统里可用的麦克风列表。

内容的提问来源于stack exchange,提问作者Daniel Mañogil Munuera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:27:26