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

Google Colab安装pyaudio遇ModuleNotFoundError问题求助

Google Colab中语音识别助手的Pyaudio安装与音频输入解决方案

问题概述

在Google Colab(Python 3.8.16)开发基础语音识别助手时,本地Visual Studio可正常运行,但Colab环境下无法安装/导入pyaudio,尝试多种安装命令后仍触发ModuleNotFoundError;同时因Colab为云端环境,无法直接通过sr.Microphone()访问本地麦克风。

已尝试的安装命令

!python --version
!pip install SpeechRecognition
!pip install pyttsx3
!pip3 install pyaudio
!pip install pipwin
!pipwin install pyaudio
!conda install -c anaconda pyaudio

import speech_recognition as sr
import pyttsx3
import pyaudio

报错信息

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-14-67c5e290f749> in <module>
      9 import speech_recognition as sr
     10 import pyttsx3
---> 11 import pyaudio
     12 
     13 # Initialize recognizer class (for recognizing the speech)

ModuleNotFoundError: No module named 'pyaudio'

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------

原始业务代码

r = sr.Recognizer()
try:
    with sr.Microphone() as mic:
        r.adjust_for_ambient_noise(mic,duration=0.1)
        audio = r.listen(mic)

        text = r.recognize_google(audio)
        text = text.lower()

        print(f"Recognized speech : {text}")
except sr.UnknownValueError:
    print("Could not understand audio")
except sr.RequestError as e:
    print("Could not request results; {0}".format(e)) 

解决步骤

1. 正确安装Pyaudio到Colab环境

Colab基于Ubuntu系统,需先安装系统级依赖,再通过pip安装:

!apt-get install -y portaudio19-dev python3-pyaudio
!pip install pyaudio

执行完成后即可正常导入pyaudio。

2. 适配Colab的音频输入逻辑(核心)

Colab无法直接访问本地麦克风,需借助Colab提供的Web端录音工具获取音频,替代sr.Microphone()的直接调用。修改后的完整代码如下:

from google.colab import output
import speech_recognition as sr
from IPython.display import Javascript, display
from base64 import b64decode

# 定义Web端录音函数
def record_audio(filename='audio.wav', duration=5):
    js = Javascript(f'''
        async function recordAudio(duration) {{
            const stream = await navigator.mediaDevices.getUserMedia({{ audio: true }});
            const recorder = new MediaRecorder(stream);
            const audioChunks = [];
            recorder.addEventListener('dataavailable', event => {{
                audioChunks.push(event.data);
            }});
            recorder.start();
            await new Promise(resolve => setTimeout(resolve, duration * 1000));
            recorder.stop();
            const audioBlob = new Blob(audioChunks, {{ type: 'audio/wav' }});
            const reader = new FileReader();
            reader.readAsDataURL(audioBlob);
            return new Promise(resolve => reader.onloadend = () => resolve(reader.result));
        }}
    ''')
    display(js)
    data = output.eval_js(f'recordAudio({duration})')
    binary = b64decode(data.split(',')[1])
    with open(filename, 'wb') as f:
        f.write(binary)
    print(f"录制完成,文件保存为 {filename}")

# 语音识别流程
r = sr.Recognizer()

# 录制音频(可自定义时长,示例为5秒)
record_audio(duration=5)

# 读取录制好的音频文件进行识别
try:
    with sr.AudioFile('audio.wav') as source:
        audio = r.record(source)
        text = r.recognize_google(audio)
        text = text.lower()
        print(f"识别结果: {text}")
except sr.UnknownValueError:
    print("无法识别音频内容")
except sr.RequestError as e:
    print(f"无法请求识别服务: {e}")

3. 简化替代方案(无需Pyaudio)

上述修改已规避对pyaudio的直接依赖,通过先录制本地音频文件、再读取识别的方式,同时解决了Colab无法访问本地麦克风的问题,无需额外导入pyaudio即可完成语音识别流程。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:30:57