I am trying to write a speech recognition code which takes voice from the microphone and process till a "Stop" is said. The code works for the first voice but then it gives an error. The code which I wrote is below:
import speech_recognition as sr
import webbrowser
r = sr.Recognizer()
with sr.Microphone() as source:
while True:
audio = r.listen(source)
print("You said " + r.recognize(audio))
if r.recognize(audio)=="Facebook":
webbrowser.open('https://www.facebook.com')
if r.recognize(audio)=="Google":
webbrowser.open('https://www.google.co.uk')
if r.recognize(audio)=="Stop":
break
The error which I am getting is :
You said Facebook
Traceback (most recent call last):
File "C:/Work/Scripts/SpeechRecognition/Speech.py", line 9, in <module>
print("You said " + r.recognize(audio)) # listen for the first phrase and extract it into audio data
File "C:\Users\roradhak.NDS-UK\AppData\Roaming\Python\Python27\site-packages\speech_recognition\__init__.py", line 324, in recognize
raise LookupError("Speech is unintelligible")
LookupError: Speech is unintelligible
Process finished with exit code 1
I think the problem might be that you call recognize many times on the same input and the first call has already consumed the audio. You can introduce one extra variable + add try/catch to handle the LookupError.
with sr.Microphone() as source:
while True:
audio = r.listen(source)
try:
result = r.recognize(audio)
print("You said " + result)
words = result.lower()
if words=="facebook":
webbrowser.open('https://www.facebook.com')
if words=="google":
webbrowser.open('https://www.google.co.uk')
if words=="stop":
break
except LookupError:
print("Please, speak more clearly")
You need to catch the exception:
def recognize(audio):
try:
return r.recognize(audio)
except LookupError, e:
print e
return ''
Then:
with sr.Microphone() as source:
while True:
audio = r.listen(source)
words = recognize(audio)
print("You said " + words)
if words == "Facebook":
webbrowser.open('https://www.facebook.com')
elif words =="Google":
webbrowser.open('https://www.google.co.uk')
elif words == "Stop":
break
Related
I have the following piece of code:
import openai
import pyttsx3
import speech_recognition as sr
from api_key import API_KEY
openai.api_key = API_KEY
engine = pyttsx3.init()
r = sr.Recognizer()
mic = sr.Microphone(device_index=1)
print(sr.Microphone.list_microphone_names())
conversation = ""
user_name = "Josode"
while True:
with mic as source:
print("\nlistening... speak clearly into mic.")
r.adjust_for_ambient_noise(source, duration=0.2)
audio = r.listen(source)
print("no longer listening.\n")
try:
user_input = r.recognize_google(audio)
except:
continue
prompt = user_name + ": " + user_input + "\n Ava:"
conversation += prompt
response = openai.Completion.create(engine="text-davinci-002", prompt=conversation, max_tokens=100)
response_str = response["choices"][0]["text"].replace("\n", "")
response_str = response_str.split(user_name + ": ", 1)[0].split("Ava: ", 1)[0]
conversation += response_str + "\n"
print(response_str)
engine.say(response_str)
engine.runAndWait()
When I run the file, I get just listening... speak clearly into mic.
no longer listening. with no output from davinci.
Also, the mic print is ['LG FULL HD', 'Ari Chan’s AirPods', 'Ari Chan’s AirPods', 'MacBook Pro Microphone', 'MacBook Pro Speakers']. I am using index 1
API key is correct and imported. I have an account at Open AI and can use playground without a problem.
Do you see something that I don't see? It should work
Most probably you are getting an exception in r.recognize_google(audio) so it forces continue again and again without any output, try to add something like this to debug it:
import traceback
...
try:
user_input = r.recognize_google(audio)
except:
print(traceback.format_exc())
continue
import speech_recognition as sr
r = sr.Recognizer()
def speaking():
try:
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
text1 = r.recognize_google(audio)
text = text1.lower()
except:
pass
return text
text = speaking()
if text == 'hello':
print("You said hello")
So yeah the code works fine. But whenever speech_recognition hears sounds like me clearing the throat/laughing/literally any ambient noise, I get an error. Can you tell me why and tell a way to correct it?
your problem.
def speaking():
try:
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
text1 = r.recognize_google(audio)
text = text1.lower()
except: # here its the problem
pass
return text # and here
the code should look like this
def speaking():
try:
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
text1 = r.recognize_google(audio)
text = text1.lower()
# or you can return text here
# and get rid of the below else block
# return text
except:
# if you get an error then do nothing
pass
# you can return None
return None
else:
# but if the try code worked then return text
return text
ofcourse you get "referenced before assignment error" because in your old code if you get an error you do nothing with it and after that you reference text, but text isnt going to be defined if you get an exception just when you are recording.
def TakeCommand():
r = sr.Recognizer
mic = sr.Microphone()
with mic as source:
print("I am listening ....")
audio = r.listen(source)
try:
print("Recognizing....")
query = r.recognize_google(audio, language = 'en-US')
print(query)
except Exception as exc:
print(exc)
print("Sorry, I didn't recognized it. Please repeat...")
TakeCommand()
I am getting an error on the line ''audio = r.listen(sourse)' It is says, let me quote 'listen() missing 1 required positional argument: 'source' ''
And in case the link to the image:
[1]: https://i.stack.imgur.com/wEYOt.png
Try changing r = sr.Recognizer to r = sr.Recognizer().
I'm doing a vocal assistant in Python 3.8 and I use a maps url to create an itinerary.
The problem is that I have an error and I have no idea how to fix it:
this is my code
def RecordAudio(ask = False):
print("micro on")
voice_data = ''
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
if ask:
print(ask)
audio = r.listen(source)
try:
voice_data = r.recognize_google(audio, language="en-EN")
print(voice_data)
respond(voice_data)
except sr.UnknownValueError:
if "" in voice_data.lower():
RecordAudio()
else:
print("Sorry, I did not understand, could you repeat ?")
RecordAudio()
except sr.RequestError:
print("I can't answer for the moment")
def respond(voice_data):
if "itineraire" in voice_data:
frommaps = RecordAudio('Where do you go from?')
tomaps = RecordAudio("Where do you go to?")
print("Calculating...")
time.sleep(1)
itineraireurl = "https://www.google.fr/maps/dir/" +frommaps +'/'+tomaps
webbrowser.get().open(itineraireurl)
And the error
File "main.py", line 86, in respond
itineraireurl = "https://www.google.fr/maps/dir/" +frommaps +'/'+tomaps
TypeError: can only concatenate str (not "NoneType") to str
itineraireurl = "https://www.google.fr/maps/dir/" +frommaps +'/'+tomaps
webbrowser.get().open(itineraireurl)
Put above line of code in form of string like below:
itineraireurl = f"https://www.google.fr/maps/dir/ {frommaps} +'/'+tomaps.webbrowser.get().open(itineraireurl)"
PS : Try to use python f string.
when i tried to run this code
import speech_recognition as sr #importing sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("speak into mic")
audio = r.listen(source,timeout=2)
try:
print("Transcription:" + r.recognize_google(audio))
except sr.UnknownValueError:
print("Audio Unintelligible")
except sr.RequestError as e:
print("cannot obtain results : {0}".format(e))
except sr.WaitTimeoutError as k :
print("time out") #error handler for time out error
when i run the above code it giving error like this
speak
into mic
Traceback (most recent call last):
File "C:/Users/punna/PycharmProjects/alex/alex.py", line 6, in <module>
audio = r.listen(source,timeout=2)
File "C:\Users\punna\Anaconda3\lib\site-packages\speech_recognition\__init__.py", line 544, in listen
raise WaitTimeoutError("listening timed out while waiting for phrase to start")
speech_recognition.WaitTimeoutError: listening timed out while waiting for phrase to start
I wrote exception but it is again giving error
can anyone help me
This might help I have just added the return "none" Statement so that it returns a none if something goes wrong and I also added phrase_time_limit to 5 and query = r.recognize_google(voice,language='en-in') this statement to recognize the words spoken by the user into a variable instead of this statement print("Transcription:" + r.recognize_google(audio)) then it worked try this might help you
r = sr.Recognizer()
with sr.Microphone() as audio:
speak('Listening...')
r.pause_threshold = 1
voice = r.listen(audio,timeout=1,phrase_time_limit=5)
try:
print("Thinking...")
query = r.recognize_google(voice,language='en-in')
print("Transcription:"+query)
except Exception as e:
print("I am Sorry There is an error while i am recognizimg your command")
return "none"
return query
It is because you kept the timeout for a limited amount of time. Try without the timeout or keep the timeout at least more than 5
def takecommand():
try:
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listing.......")
r.pause_threshold = 1
audio = r.listen(source, timeout=1, phrase_time_limit=5)
except Exception as e:
speak("error in my files sir restarting")
speak("completed")
return "none"
try:
print("Recognize......")
qureay = r.recognize_google(audio, language='en-in')
print("user said:" +qureay)
except Exception as e:
speak("Say That Again Please...")
return "none"
return qureay