Hi guys I'm trying to trigger the while loop in my code that starts speech recognition whenever the hotword "virgo" is said. The problem is that snowboy detects the hotword but I don't know how to execute the "while" loop once the hotword is triggered. Any help please? this may sound stupid and should be relatively easy but my brain is on fire right now. thank you!
import speech_recognition as sr
from textblob import TextBlob
import snowboydecoder
recognizer_instance = sr.Recognizer()
def detected_callback():
print ("tell me!")
detector = snowboydecoder.HotwordDetector("virgo.pmdl",sensitivity=0.5)
detector.start(detected_callback=snowboydecoder.play_audio_file,sleep_time=0.03)
detector.terminate()
while True:
with sr.Microphone() as source:
recognizer_instance.adjust_for_ambient_noise(source)
print("Listening...")
audio = recognizer_instance.listen(source)
print("copy that!")
try:
text = recognizer_instance.recognize_google(audio, language = "it-IT")
print("you said:\n", text)
except Exception as e:
break
Your while loop is always 'triggered', given the TRUE, until you break out of it. To trigger the code within the loop, do, for example:
while True:
if YOUR_TRIGGER_CONDITION:
with sr.Microphone() as source:
recognizer_instance.adjust_for_ambient_noise(source)
print("Listening...")
audio = recognizer_instance.listen(source)
print("copy that!")
try:
text = recognizer_instance.recognize_google(audio, language = "it-IT")
print("you said:\n", text)
except Exception as e:
break
Related
I am building a simple AI assistant in python and so far everything has worked pretty well. The voice recognition and text to speech are working also fine. I wanted to make it work like, I am going to speak something and depending on the input it would answer some simple questions. But with the if statement I tried to make conditions depending on the input but it doesn't get executed instead the else statement gets executed.
import speech_recognition as sr
import pyttsx3
engine = pyttsx3.init()
listener = sr.Recognizer()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty("rate", 178)
def talk(text):
engine.say(text)
print(text)
engine.runAndWait()
def command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
print(command)
except:
pass
command = ''
return command
def run():
data = command()
if 'hello' in data:
talk('Hello')
elif 'who are you' in data:
talk('I am an AI.')
else:
talk("I couldn't hear it.")
while True:
run()
I have tried to use it without a function but still the same problem. It doesn't work even if the if statement is true.
I think you wanted to put the command = '' in the except block. It is an indentation error.
When i run this code and speak script return empty list:
import pyaudio
import pyttsx3
import os
import pyautogui
import speech_recognition as sr
def command():
r = sr.Recognizer()
mic = sr.Microphone()
recog = sr.Recognizer()
with mic as u_audio:
print('Speak please')
r.adjust_for_ambient_noise(u_audio)
voice = r.listen(u_audio)
try:
listening = recog.recognize_google(voice, language = 'en-EN', show_all = True)
print(listening)
except Exception as e:
print('I not understand' + str(e))
command()
command()
output:
speak please
[ ]
i do not understand, why list are empty. Maybe i should choose microphone index.
The Microphone is the Problem
The problem should be possibly be on the Microphone, because I ran the same code, and it does give the Output, it gives all possible outcomes of the speech.
Anyways, it isn't efficient. Unwanted libraries slows it down, here is the updated code:
import pyttsx3
import speech_recognition as sr
def command():
r = sr.Recognizer()
mic = sr.Microphone()
recog = sr.Recognizer()
with mic as u_audio:
r.adjust_for_ambient_noise(u_audio)
print('Speak please')
voice = r.listen(u_audio)
try:
listening = recog.recognize_google(voice, language = 'en-EN', show_all = True)
print(listening)
except Exception as e:
print('I not understand' + str(e))
command()
command()
Comment down the result!
I am actually the member of NLI(Novitatis Locus Industries) and our team seems to get some issues. While designing a voice enabled program with GUI, tkinter's mainloop seems to be giving us some issues. See our code-
//this function defines the gui//
def gui():
gui_kurooto = Tk()
txt_dsply_var = StringVar()
AUTHN_LBL = Label(gui_kurooto, text=txt_dsply_var)
AUTHN_LBL.pack()
gui_kurooto.mainloop()
//this code defines the microphone input//
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
txt_dsply_var = StringVar()
txt_dsply_var.set('Listening')//display listening on gui//
r.pause_threshold = 1
r.energy_threshold = 10000
audio = r.listen(source)
try:
print("Recognizing...")
txt_dsply_var = StringVar()
txt_dsply_var.set('Recognizing')//display recognizing//
query = r.recognize_google(audio, language='en-en')
print(f"User said: {query}\n")
txt_dsply_var = StringVar()
txt_dsply_var.set(f"User said: {query}\n")//display input//
except Exception as e:
# print(e)
print("Say that again please...")
return "None"
return query
//to run//
if __name__ == "__main__":
gui()
while True:
# if 1:
query = takeCommand().lower()
Now when I try to run this, the code never reaches the while loop. I know the mainloop is an infinite loop but is there a substitute present their so I can let it reach other functions. Keeping the function out of function also dosen't work. Can I place it after the query command?
Also I have other question, is there a way by which I can spectra according to the voice input like Google and Siri have bars which move when we speak?
Any help would be appreciated.
Whenever i run this code, and tell start the function "google", it goes back to another function. i have tried to do this for a few days now, and still no luck. any help would be appreciated:)
import webbrowser
import string
import time
import pyttsx3
import speech_recognition as sr
engine = pyttsx3.init()
r = sr.Recognizer()
def Listen():
with sr.Microphone() as sourceL:
print("Listening...")
Open = r.listen(sourceL, phrase_time_limit=2)
try:
if "Nova" in r.recognize_google(Open):
print("Nova Recieved...")
Command()
else:
Listen()
except:
Listen()
def Google():
print("what would you like me to search for you? ")
engine.say("what would you like me to search for you? ")
engine.runAndWait()
with sr.Microphone as source:
Search = r.listen(source)
Search = r.recognize(Search)
The code will go back to Listen() at with sr.Mirophone as source
This is how I am calling google()...
def Command():
print("You called me?")
engine.say("you called me? ")
engine.runAndWait()
Cr = sr.Recognizer()
with sr.Microphone() as source:
print("Listening For Command...")
CommandToDo = Cr.listen(source, phrase_time_limit=2)
print("...")
if "YouTube" in Cr.recognize_google(CommandToDo):
YouTube()
elif "Google" in Cr.recognize_google(CommandToDo):
Google()
else:
print("Command not recognized>> " + r.recognize_google(CommandToDo))
There is a function argument phrase_time_limit you need to specify while calling the listen method inside Google function.
phrase_time_limit represents the wait time of the program, for how many seconds it will wait for the user to give input. Here it will wait for 2 seconds. If you do not give any time limit it will wait indefinitely.
From the source code documentation:
The phrase_time_limit parameter is the maximum number of seconds
that this will allow a phrase to continue before stopping and
returning the part of the phrase processed before the time limit was
reached. The resulting audio will be the phrase cut off at the time
limit. If phrase_timeout is None, there will be no phrase time
limit.
To clarify on the timeout argument
The timeout parameter is the maximum number of seconds that this
will wait for a phrase to start before giving up and throwing an
speech_recognition.WaitTimeoutError exception. If timeout is
None, there will be no wait timeout.
For more details check the source code.
def Google():
print("what would you like me to search for you? ")
engine.say("what would you like me to search for you? ")
engine.runAndWait()
with sr.Microphone() as source:
Search = r.listen(source, phrase_time_limit=2) # <-- Here
Search = r.recognize_google(Search)
print(Search)
After this change, it is working for me.
Check it is
with sr.Microphone() as source: not
with sr.Microphone as source:. You missed the braces.
I am writing a basic talking tom like code which listens to the person and repeats its audio along side i want it to display the text which the speaker has spoken.
the problem I'm facing is i am not able to use the print and listen command simultaneously.
I need to speak the phrase twice i.e, once for printing it on screen and other time for repeating it.
I want to figure it these both things to happen only at once i.e, the audio should be repeated and displayed at the same time without me repeating the phrase twice.
import speech_recognition
import pyttsx
speech_engine = pyttsx.init()
speech_engine.setProperty('rate', 150)
def speak(text):
speech_engine.say(text)
speech_engine.runAndWait()
recognizer = speech_recognition.Recognizer()
def listen():
with speech_recognition.Microphone() as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
return recognizer.recognize_google(audio)
except speech_recognition.UnknownValueError:
print("Could not understand audio")
except speech_recognition.RequestError as e:
print("Recog Error; {0}".format(e))
return ""
speak("Say something!")
print (listen())
speak("I heard you say " + listen())
speak("Say something!")
text = listen()
speak("I heard you say " + text)
Write:
print(audio)
Under:
return recognizer.recognize_google(audio)