"OSError: No Default Input Device Available" on Google Colab

"OSError: No Default Input Device Available" on Google Colab

我根据 的回答在 Google Colab 上使用“pip3 install pyaudio”安装了 pyaudio。

然后,我得到了这个错误,

OSError: No Default Input Device Available

在 Google Colab 上。

代码如下所示。

import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
    r.adjust_for_ambient_noise(source)
    audio = r.listen(source)

您不能像使用自己的机器那样直接使用 Google Colab 中的麦克风。您必须使用 JavaScript 让浏览器启用麦克风。这可以使用找到的以下代码完成 here:

# all imports
from io import BytesIO
from base64 import b64decode
from google.colab import output
from IPython.display import Javascript

RECORD = """
const sleep  = time => new Promise(resolve => setTimeout(resolve, time))
const b2text = blob => new Promise(resolve => {
  const reader = new FileReader()
  reader.onloadend = e => resolve(e.srcElement.result)
  reader.readAsDataURL(blob)
})
var record = time => new Promise(async resolve => {
  stream = await navigator.mediaDevices.getUserMedia({ audio: true })
  recorder = new MediaRecorder(stream)
  chunks = []
  recorder.ondataavailable = e => chunks.push(e.data)
  recorder.start()
  await sleep(time)
  recorder.onstop = async ()=>{
    blob = new Blob(chunks)
    text = await b2text(blob)
    resolve(text)
  }
  recorder.stop()
})
"""

def record(sec=3):
  print("Speak Now...")
  display(Javascript(RECORD))
  sec += 1
  s = output.eval_js('record(%d)' % (sec*1000))
  print("Done Recording !")
  b = b64decode(s.split(',')[1])
  return b #byte stream

现在您可以使用record()功能来录制音频了。此函数 returns 将音频作为字节流。您可以按照 link:

在 colab 上自己尝试