pip3 install pyaudio on Google Colab

断了今生、忘了曾经 提交于 2021-02-07 08:35:28

问题


I install pyaudio by "pip3 install pyaudio" on Google Colab successfully by the answer from angelokh's. Then, I got the error,

OSError: No Default Input Device Available

on Google Colab.

The code is below.

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

回答1:


You can't use the mic from Google Colab directly as you do with your own machine. You have to use JavaScript to let the browser enable the mic. This can be done using the following code found 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

Now you can use the record() function to record the audio. This function returns the audio as byte-stream. You can try it yourself on colab following this link:



来源:https://stackoverflow.com/questions/59013743/pip3-install-pyaudio-on-google-colab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!