树莓派运行Python speech_recognition语音识别程序报错无法使用如何解决
Python语音识别ALSA报错修复方案
故障根因
报错中大量ALSA相关日志是因为运行设备(大概率为树莓派)默认优先调用HDMI音频输出设备,你配置的摄像头麦克风未被speech_recognition库默认识别,同时未做环境噪音校准,最终导致收音失败、识别报错。
修复步骤
- 第一步:查询你的麦克风设备编号
运行终端命令:
在输出列表中找到你的摄像头麦克风对应的arecord -lcard号和device号,示例输出中card 1: U0x46d0x821 [USB Device 0x46d:0x821], device 0: USB Audio [USB Audio]对应的card号为1,device号为0。 - 第二步:确认speech_recognition库对应的麦克风索引
运行以下代码打印所有可识别的麦克风设备:
找到你的摄像头麦克风对应的索引值备用。import speech_recognition as sr for index, name in enumerate(sr.Microphone.list_microphone_names()): print(f"设备索引{index}: {name}") - 第三步:修改原有代码,指定麦克风设备并增加环境噪音校准
修复后的完整代码如下:import speech_recognition as sr # 可选:屏蔽ALSA警告输出 import os import ctypes ERROR_HANDLER_FUNC = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p) def py_error_handler(filename, line, function, err, fmt): pass c_error_handler = ERROR_HANDLER_FUNC(py_error_handler) try: asound = ctypes.cdll.LoadLibrary('libasound.so.2') asound.snd_lib_error_set_handler(c_error_handler) except: pass print('Speech Recognition ready!') r = sr.Recognizer() # 此处device_index替换为你第二步查到的麦克风索引 with sr.Microphone(device_index=1) as source: # 增加环境噪音校准 r.adjust_for_ambient_noise(source, duration=0.5) print('Listening...') audio = r.listen(source) try: text = r.recognize_google(audio, language='zh-CN') # 可指定中文识别 print('You said: {}'.format(text)) except Exception as e: print('Failed to recognize voice, error:', str(e)) - 第四步:验证麦克风硬件可用性
若修改后仍识别失败,先运行终端命令测试麦克风是否能正常录音(命令中plughw:1,0的1和0替换为你第一步查到的card号和device号):
如果播放无声音,先排查麦克风硬件连接、ALSA输入配置是否正确。arecord -D plughw:1,0 -d 3 test.wav aplay test.wav
内容的提问来源于stack exchange,提问作者RockZombie
相关产品推荐
相关产品推荐

