I was trying the below speech recognition code using Google Speech API.
#!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
# Speech recognition using Google Speech Recognition
try:
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
But I am getting only this.
jobin@jobin-Satellite-A665:~/scr$ python3 scr.py
Say something!
Even though I say something, nothing happens.
I don't have an external microphone. I think this script will work with my laptop's in-built microphone.
I have tested my laptop's microphone here. It is working fine.
Am I missing anything?
You could test that pyAudio is finding your microphone by running the following:
"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
And playing the resulting output.wav
file.
Once you are confident that you are getting some audio I would add a couple of print statements to the original code to locate how far you are getting, i.e.:
print("Audio captured!") # before trying to recognise see if you have something
and
print('Recognition Ended') # at the end of the script
This will let you see how far you are getting.
Next you may need to find out which is the default audio device with:
import pyaudio
print(pyaudio.pa.get_default_input_device())
Which should tell you the default input device, this was one on my machine so used this:
with sr.Microphone(1) as source: # Specify which input device to use
r.adjust_for_ambient_noise(source, 1) # Adjust for ambient
print("Say something!")
audio = r.listen(source, 2) # 2 Second time out
print('Done Listening sample size =', len(audio.frame_data))