Python speech_recognition.RequestError() Examples

The following are 30 code examples of speech_recognition.RequestError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module speech_recognition , or try the search function .
Example #1
Source File: benji.py    From B.E.N.J.I. with MIT License 12 votes vote down vote up
def OnClicked(self):
		"""Recognizes the audio and sends it for display to displayText."""
		r = sr.Recognizer()
		with sr.Microphone() as source:
			speak.say('Hey I am Listening ')
			speak.runAndWait()
			audio = r.listen(source)
		try:
			put=r.recognize_google(audio)

			self.displayText(put)
			self.textBox.insert('1.2',put)
			self.textBox.delete('1.2',tk.END)
			events(self,put)
		except sr.UnknownValueError:
			self.displayText("Could not understand audio")
		except sr.RequestError as e:
			self.displayText("Could not request results; {0}".format(e)) 
Example #2
Source File: client_reverse.py    From Adeept_PiCar-B_oldversion with GNU General Public License v3.0 8 votes vote down vote up
def voice_input():
    global a2t
    r = sr.Recognizer()
    with sr.Microphone() as source:
        #r.adjust_for_ambient_noise(source)
        r.record(source,duration=2)
        print("Say something!")
        audio = r.listen(source)
    try:
        a2t=r.recognize_sphinx(audio,keyword_entries=[('forward',1.0),('backward',1.0),('left',1.0),('right',1.0),('stop',1.0),('find line',0.95),('follow',1),('lights on',1),('lights off',1)])
        print("Sphinx thinks you said " + a2t)
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))
    BtnVIN.config(fg=color_text,bg=color_btn)
    return a2t 
Example #3
Source File: benji.py    From B.E.N.J.I. with MIT License 8 votes vote down vote up
def OnClicked(self):
		"""Recognizes the audio and sends it for display to displayText."""
		r = sr.Recognizer()
		with sr.Microphone() as source:
			system('say Hey I am Listening ')
			
			audio = r.listen(source)
		try:
			put=r.recognize_google(audio)

			self.displayText(put)
			self.textBox.insert('1.2',put)
			put=put.lower()
			put = put.strip()
			#put = re.sub(r'[?|$|.|!]', r'', put)
			link=put.split()
			events(self,put,link)
		except sr.UnknownValueError:
			self.displayText("Could not understand audio")
		except sr.RequestError as e:
			self.displayText("Could not request results; {0}".format(e)) 
Example #4
Source File: voice_recognition.py    From speech_recognition_chatbot with MIT License 7 votes vote down vote up
def recognize_speech_from_mic(recognizer, microphone):
    """Transcribe speech from recorded from `microphone`.

    Returns a dictionary with three keys:
    "success": a boolean indicating whether or not the API request was
               successful
    "error":   `None` if no error occured, otherwise a string containing
               an error message if the API could not be reached or
               speech was unrecognizable
    "transcription": `None` if speech could not be transcribed,
               otherwise a string containing the transcribed text
    """
    # check that recognizer and microphone arguments are appropriate type
    if not isinstance(recognizer, sr.Recognizer):
        raise TypeError("`recognizer` must be `Recognizer` instance")

    if not isinstance(microphone, sr.Microphone):
        raise TypeError("`microphone` must be `Microphone` instance")

    # adjust the recognizer sensitivity to ambient noise and record audio
    # from the microphone
    with microphone as source:
        recognizer.adjust_for_ambient_noise(source) # #  analyze the audio source for 1 second
        audio = recognizer.listen(source)

    # set up the response object
    response = {
        "success": True,
        "error": None,
        "transcription": None
    }

    # try recognizing the speech in the recording
    # if a RequestError or UnknownValueError exception is caught,
    #   update the response object accordingly
    try:
        response["transcription"] = recognizer.recognize_google(audio)
    except sr.RequestError:
        # API was unreachable or unresponsive
        response["success"] = False
        response["error"] = "API unavailable/unresponsive"
    except sr.UnknownValueError:
        # speech was unintelligible
        response["error"] = "Unable to recognize speech"

    return response

#%% 
Example #5
Source File: gen_sentence_with_emoticons.py    From Real-Time-Facial-Expression-Recognition-with-DeepLearning with MIT License 7 votes vote down vote up
def speechRecognition():
    # obtain audio from the microphone 
    print("Press 'y' to start~")
    inputdata = input()
    if inputdata == 'y':
        inputdata = 0
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say something!")
            audio = r.listen(source)
        # recognize speech 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)`
            recSuccess = 1
            recContent = r.recognize_google(audio)
            print("Speech Recognition thinks you said " + recContent)#,language="cmn-Hant-TW")
            return recContent
        except sr.UnknownValueError:
            print("Could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition service; {0}".format(e)) 
Example #6
Source File: client.py    From Adeept_PiCar-B_oldversion with GNU General Public License v3.0 7 votes vote down vote up
def voice_input():
    global a2t
    r = sr.Recognizer()
    with sr.Microphone() as source:
        #r.adjust_for_ambient_noise(source)
        r.record(source,duration=2)
        print("Say something!")
        audio = r.listen(source)
    try:
        a2t=r.recognize_sphinx(audio,keyword_entries=[('forward',1.0),('backward',1.0),('left',1.0),('right',1.0),('stop',1.0),('find line',0.95),('follow',1),('lights on',1),('lights off',1)])
        print("Sphinx thinks you said " + a2t)
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))
    BtnVIN.config(fg=color_text,bg=color_btn)
    return a2t 
Example #7
Source File: speechtotext.py    From GROOT with Mozilla Public License 2.0 7 votes vote down vote up
def listen():
    #obtain audio from the microphone
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say something!")
        r.adjust_for_ambient_noise(source, duration=0.5)
        audio = r.listen(source)
    #recognize speech using Google Speech Recognition
    try:
        var=r.recognize_google(audio)
    except sr.UnknownValueError:
        var="Groot could not understand audio"
    except sr.RequestError:
        var=" Looks like, there is some problem with Google Speech Recognition"

    return var

    #will show all posible text from audio
    #print(r.recognize_google(audio, show_all=True)) 
Example #8
Source File: benji.py    From B.E.N.J.I. with MIT License 7 votes vote down vote up
def OnClicked(self):
		"""Recognizes the audio and sends it for display to displayText."""
		r = sr.Recognizer()
		with sr.Microphone() as source:
			speak.say('Hey I am Listening ')
			speak.runAndWait()
			audio = r.listen(source)
		try:
			put=r.recognize_google(audio)
			self.displayText(put)
			self.textBox.insert('1.2',put)
			self.textBox.delete('1.2',tk.END)
			events(self,put)
		except sr.UnknownValueError:
			self.displayText("Could not understand audio")
		except sr.RequestError as e:
			self.displayText("Could not request results; {0}".format(e)) 
Example #9
Source File: speechtotext.py    From SaltwashAR with GNU General Public License v3.0 7 votes vote down vote up
def convert(self):

        with sr.Microphone() as source:
            print "listening..."
            audio = self.recognizer.listen(source)

        text = None

        try:
            text = self.recognizer.recognize_google(audio)
            print text
        except sr.UnknownValueError:
            print "Google Speech Recognition could not understand audio"
        except sr.RequestError:
            print "Could not request results from Google Speech Recognition service"

        return text 
Example #10
Source File: neuraldata.py    From SaltwashAR with GNU General Public License v3.0 6 votes vote down vote up
def _get_target(recognizer, audio):
    target = None
    text = None

    # use Google Speech Recognition to resolve audio to Yes or No
    try:
        text = recognizer.recognize_google(audio).lower()
        print text
    except sr.UnknownValueError:
        print "Google Speech Recognition could not understand audio"
    except sr.RequestError:
        print "Could not request results from Google Speech Recognition service"

    if not text: return

    # obtain target data i.e. 0 for Yes, 1 for No
    try:
        target = AUDIO_CLASSES.index(text)
    except ValueError:
        return

    return target

# get neural network input data 
Example #11
Source File: smartmirror-bing.py    From Smart-Mirror with MIT License 6 votes vote down vote up
def start_speech_recording(tmp): 
# Record Audio
    global recognised_speech
    BING_KEY = "cfee7d6db79d4671b9cea936da4689d7" 
    while True:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say something!")
            r.adjust_for_ambient_noise(source, duration = 1)
            audio = r.listen(source)
        
        try:
            recognised_speech = r.recognize_bing(audio, key=BING_KEY).lower()
            print("Microsoft Bing Voice Recognition thinks you said:" + recognised_speech)
            if "hallo" in recognised_speech or "wakeup" in recognised_speech or "start" in recognised_speech or "makeup" in recognised_speech or "star" in recognised_speech or "breakup" in recognised_speech:
                thread.start_new_thread( face_identify, (3, ) )       
        except sr.UnknownValueError:
            print("Microsoft Bing Voice Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Microsoft Bing Voice Recognition service; {0}".format(e)) 
Example #12
Source File: apis.py    From asr-study with MIT License 6 votes vote down vote up
def recognize_from_api(audio, api, name='API', safe=True, **kwargs):
    if not isinstance(audio, sr.AudioData):
        with sr.AudioFile(audio) as source:
            audio = r.record(source)
    try:
        return api(audio, **kwargs)
    except sr.UnknownValueError as e:
        if not safe:
            raise e
        return "\t%s could not understand audio" % name
    except sr.RequestError as e:
        if not safe:
            raise e
        return "\tCould not request results from %s \
    service; {0}" % (name, e) 
Example #13
Source File: speech_to_text.py    From aipa with MIT License 6 votes vote down vote up
def main():
	# obtain audio from the microphone
	while True:
	    r = sr.Recognizer()
	    with sr.Microphone() as source:
		print("listening...")		
		audio = r.listen(source)
		print("sa")
	    # recognize speech 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("as")		
		command = r.recognize_google(audio)
		print("You said: " + command)
		
	    #exception handling
	    except sr.UnknownValueError:
		print("I could not understand audio")
	    except sr.RequestError as e:
		print("Could not request results from Speech Recognition service; {0}".format(e)) 
Example #14
Source File: smartmirror.py    From Smart-Mirror with MIT License 6 votes vote down vote up
def start_speech_recording(tmp): 
# Record Audio
    global recognised_speech 
    while True:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say something!")
            r.adjust_for_ambient_noise(source, duration = 1)
            audio = r.listen(source)
        
        try:
            recognised_speech = r.recognize_google(audio).lower()
            print("You said: " + r.recognize_google(audio))
            if "hallo" in recognised_speech or "wakeup" in recognised_speech or "start" in recognised_speech or "makeup" in recognised_speech or "star" in recognised_speech or "breakup" in recognised_speech:
                thread.start_new_thread( face_identify, (3, ) )       
        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)) 
Example #15
Source File: VoiceEngineServer.py    From rpi-course with MIT License 6 votes vote down vote up
def Listener():
    global broadcastMSG
    while(1):
        # obtain audio from the microphone
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say something!")
            audio = r.listen(source)

        # recognize speech using Google Speech Recognition
        try:
            recognizedCommand = r.recognize_google(audio);
            print("Google Speech Recognition thinks you said " + recognizedCommand)
            if(recognizedCommand == "start"):
                broadcastMSG = "start"
            elif(recognizedCommand == "stop"):
                broadcastMSG = "stop"
            elif(recognizedCommand == "clockwise"):
                broadcastMSG = "clockwise"
            elif(recognizedCommand == "counter clockwise"):
                broadcastMSG = "counter clockwise"
        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)) 
Example #16
Source File: friday.py    From Friday with MIT License 6 votes vote down vote up
def _google_stt(self):
        """
        Uses Google's Speech to Text engine to
        understand speech and convert it into
        text.
        :return: String, either the spoken text or error text.
        """
        click.echo("Please speak now")
        # Listen to the microphone set up in the __init__ file.
        with self.microphone as mic_source:
            audio = self.recognizer.listen(mic_source)
        click.echo("Processing audio")
        try:
            # Try to recognize the text
            return self.recognizer.recognize_google(audio, show_all=self.debugging)
        except sr.UnknownValueError:  # speech is unintelligible
            return "Google could not understand the audio."
        except sr.RequestError:
            return "Could not request results from Google's speech recognition service." 
Example #17
Source File: rebreakcaptcha.py    From rebreakcaptcha with MIT License 6 votes vote down vote up
def speech_to_text(self, audio_source):
        # Initialize a new recognizer with the audio in memory as source
        recognizer = sr.Recognizer()
        with sr.AudioFile(audio_source) as source:
            audio = recognizer.record(source) # read the entire audio file

        audio_output = ""
        # recognize speech using Google Speech Recognition
        try:
            audio_output = recognizer.recognize_google(audio)
            print("[{0}] Google Speech Recognition: ".format(self.current_iteration) + audio_output)
            # Check if we got harder audio captcha
            if any(character.isalpha() for character in audio_output):
                # Use Houndify to detect the harder audio captcha
                print("[{0}] Fallback to Houndify!".format(self.current_iteration))
                audio_output = self.string_to_digits(recognizer.recognize_houndify(audio, client_id=HOUNDIFY_CLIENT_ID, client_key=HOUNDIFY_CLIENT_KEY))
                print("[{0}] Houndify: ".format(self.current_iteration) + audio_output)
        except sr.UnknownValueError:
            print("[{0}] Google Speech Recognition could not understand audio".format(self.current_iteration))
        except sr.RequestError as e:
            print("[{0}] Could not request results from Google Speech Recognition service; {1}".format(self.current_iteration).format(e))
            
        return audio_output 
Example #18
Source File: google.py    From kalliope with GNU General Public License v3.0 6 votes vote down vote up
def google_callback(self, recognizer, audio):
        """
        called from the background thread
        """
        try:
            captured_audio = recognizer.recognize_google(audio,
                                                         key=self.key,
                                                         language=self.language,
                                                         show_all=self.show_all)
            Utils.print_success("Google Speech Recognition thinks you said %s" % captured_audio)
            self._analyse_audio(audio_to_text=captured_audio)
        except sr.UnknownValueError:
            Utils.print_warning("Google Speech Recognition could not understand audio")
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except sr.RequestError as e:
            Utils.print_danger("Could not request results from Google Speech Recognition service; {0}".format(e))
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except AssertionError:
            Utils.print_warning("No audio caught from microphone")
            self._analyse_audio(audio_to_text=None) 
Example #19
Source File: bing.py    From kalliope with GNU General Public License v3.0 6 votes vote down vote up
def bing_callback(self, recognizer, audio):
        """
        called from the background thread
        """
        try:
            captured_audio = recognizer.recognize_bing(audio,
                                                       key=self.key,
                                                       language=self.language,
                                                       show_all=self.show_all)
            Utils.print_success("Bing Speech Recognition thinks you said %s" % captured_audio)
            self._analyse_audio(captured_audio)

        except sr.UnknownValueError:
            Utils.print_warning("Bing Speech Recognition could not understand audio")
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except sr.RequestError as e:
            Utils.print_danger("Could not request results from Bing Speech Recognition service; {0}".format(e))
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except AssertionError:
            Utils.print_warning("No audio caught from microphone")
            self._analyse_audio(audio_to_text=None) 
Example #20
Source File: cmusphinx.py    From kalliope with GNU General Public License v3.0 6 votes vote down vote up
def sphinx_callback(self, recognizer, audio):
        """
        called from the background thread
        """
        try:
            captured_audio = recognizer.recognize_sphinx(audio,
                                                         language=self.language,
                                                         keyword_entries=self.keyword_entries,
                                                         grammar=self.grammar_file)
            Utils.print_success("Sphinx Speech Recognition thinks you said %s" % captured_audio)
            self._analyse_audio(captured_audio)

        except sr.UnknownValueError:
            Utils.print_warning("Sphinx Speech Recognition could not understand audio")
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except sr.RequestError as e:
            Utils.print_danger("Could not request results from Sphinx Speech Recognition service; {0}".format(e))
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except AssertionError:
            Utils.print_warning("No audio caught from microphone")
            self._analyse_audio(audio_to_text=None) 
Example #21
Source File: wit.py    From kalliope with GNU General Public License v3.0 6 votes vote down vote up
def wit_callback(self, recognizer, audio):
        try:
            captured_audio = recognizer.recognize_wit(audio,
                                                      key=self.key,
                                                      show_all=self.show_all)
            Utils.print_success("Wit.ai Speech Recognition thinks you said %s" % captured_audio)
            self._analyse_audio(captured_audio)

        except sr.UnknownValueError:
            Utils.print_warning("Wit.ai Speech Recognition could not understand audio")
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except sr.RequestError as e:
            Utils.print_danger("Could not request results from Wit.ai Speech Recognition service; {0}".format(e))
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except AssertionError:
            Utils.print_warning("No audio caught from microphone")
            self._analyse_audio(audio_to_text=None) 
Example #22
Source File: audio.py    From uncaptcha with MIT License 6 votes vote down vote up
def ibm(audio, vals, i, results_dict, timing, show_all=False):
	# recognize speech using IBM Speech to Text
	IBM_USERNAME = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"  # IBM Speech to Text usernames are strings of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
	IBM_PASSWORD = "XXXXXXXXXX"  # IBM Speech to Text passwords are mixed-case alphanumeric strings
	try:
		s = time.time()
		#print("IBM Speech to Text: ")
		vals[i] = text_to_num(r.recognize_ibm(audio, username=IBM_USERNAME, \
		password=IBM_PASSWORD, show_all=False), "ibm", results_dict)
		timing["ibm"].append(time.time() - s)
	except sr.UnknownValueError:
		logging.debug("IBM Speech to Text could not understand audio")
		results_dict["ibm"] = [DEFAULT]
		results_dict["ibm_fil"] = [DEFAULT]
	except sr.RequestError as e:
		logging.debug("Could not request results from IBM Speech to Text service; {0}".format(e))
		results_dict["ibm"] = [DEFAULT]
		results_dict["ibm_fil"] = [DEFAULT]
#Query Google Speech-To-Text 
Example #23
Source File: audio.py    From uncaptcha with MIT License 6 votes vote down vote up
def bing(audio, vals, i, results_dict, timing):
	# recognize speech using Microsoft Bing Voice Recognition
	# Microsoft Bing Voice Recognition API keys 32-character lowercase hexadecimal strings
		
	BING_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
	try:
		s = time.time()
		#print("Microsoft Bing Voice Recognition: ")
		vals[i] = text_to_num(r.recognize_bing(audio, key=BING_KEY), "bing", results_dict)
		timing["bing"].append(time.time() - s)
	except sr.UnknownValueError:
		logging.debug("Microsoft Bing Voice Recognition could not understand audio")
		results_dict["bing"] = [DEFAULT]
		results_dict["bing_fil"] = [DEFAULT]
	except sr.RequestError as e:
		logging.debug("Could not request results from Microsoft Bing Voice Recognition service; {0}".format(e))
		results_dict["bing"] = [DEFAULT]
		results_dict["bing_fil"] = [DEFAULT]
# Query IBM 
Example #24
Source File: audio.py    From uncaptcha with MIT License 6 votes vote down vote up
def wit(audio, vals, i, results_dict, timing):
	# recognize speech using Wit.ai
	WIT_AI_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"  # Wit.ai keys are 32-character uppercase alphanumeric strings
	try:
		s = time.time()
		#print("Wit.ai: ")
		vals[i] = text_to_num(r.recognize_wit(audio, key=WIT_AI_KEY), "wit", results_dict)
		timing["wit"].append(time.time() - s)
		#print("Wit " + str(vals[i]))
	except sr.UnknownValueError:
		logging.debug("Wit.ai could not understand audio")
		results_dict["wit"] = [DEFAULT]
		results_dict["wit_fil"] = [DEFAULT]
	except sr.RequestError as e:
		logging.debug("Could not request results from Wit.ai service; {0}".format(e))
		results_dict["wit"] = [DEFAULT]
		results_dict["wit_fil"] = [DEFAULT]
#Query Bing 
Example #25
Source File: audio.py    From uncaptcha with MIT License 6 votes vote down vote up
def sphinx(audio, vals, i, results_dict, timing):
	try:
		#print("Sphinx: ")
		s = time.time()
		vals[i] = text_to_num(r.recognize_sphinx(audio), "sphinx", results_dict)
		timing["sphinx"].append(time.time() - s)
		print "timing2", timing
	except sr.UnknownValueError:
		logging.debug("Sphinx could not understand audio")
		results_dict["sphinx"] = [DEFAULT]
		results_dict["sphinx_fil"] = [DEFAULT]
	except sr.RequestError as e:
		logging.debug("Sphinx error; {0}".format(e))
		results_dict["sphinx"] = [DEFAULT]
		results_dict["sphinx_fil"] = [DEFAULT]
#Query Google Cloud 
Example #26
Source File: apiai.py    From kalliope with GNU General Public License v3.0 5 votes vote down vote up
def apiai_callback(self, recognizer, audio):
        """
        called from the background thread
        :param recognizer:
        :param audio:
        :return:
        """
        try:
            captured_audio = recognizer.recognize_api(audio,
                                                      client_access_token=self.key,
                                                      language=self.language,
                                                      session_id=self.session_id,
                                                      show_all=self.show_all)
            Utils.print_success("Apiai Speech Recognition thinks you said %s" % captured_audio)
            self._analyse_audio(captured_audio)

        except sr.UnknownValueError as e:
            Utils.print_warning("Apiai Speech Recognition could not understand audio; {0}".format(e))
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except sr.RequestError as e:
            Utils.print_danger("Could not request results from Apiai Speech Recognition service; {0}".format(e))
            # callback anyway, we need to listen again for a new order
            self._analyse_audio(audio_to_text=None)
        except AssertionError:
            Utils.print_warning("No audio caught from microphone")
            self._analyse_audio(audio_to_text=None) 
Example #27
Source File: brain.py    From Jarvis with GNU General Public License v3.0 5 votes vote down vote up
def Listen(self):
		with sr.Microphone() as source:
			self.audio = self.rec.listen(source)
		try:
			self.result = self.rec.recognize_google(self.audio)
			print self.result
			return self.result
		except sr.UnknownValueError:
        	        print("Google Speech Recognition could not understand audio")
        	except sr.RequestError:
                	self.Say("Could not request results from Google Speech Recognition service master, check our internet connection.") 
Example #28
Source File: voice.py    From Hindi-DateTime-Parser with MIT License 5 votes vote down vote up
def voice_input():
    
    #!/usr/bin/env python3
    # Requires PyAudio and PySpeech.
    
	#sudo apt-get install portaudio19-dev

	#pip install --allow-unverified=pyaudio pyaudio 
	
	#requires internet too

    import speech_recognition as sr
     
    # Record Audio
    r = sr.Recognizer()
    m = sr.Microphone()

    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)`
        a=r.recognize_google(audio)
        #time.sleep(1)
        
        #stop_listening = r.listen_in_background(m, callback)
       
    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))

    print (a)
    return a 
Example #29
Source File: speech_recognition.py    From macaw with MIT License 5 votes vote down vote up
def speech_to_text(self, file_path):
        print(file_path)
        wav_file_name = ogg_to_wav(file_path)
        with sr.AudioFile(wav_file_name) as source:
            audio = self.asr.record(source)
        try:
            text = self.asr.recognize_google(audio)
            os.remove(wav_file_name)
            return text
        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)) 
Example #30
Source File: speech_to_text.py    From respeaker_ros with Apache License 2.0 5 votes vote down vote up
def audio_cb(self, msg):
        if self.is_canceling:
            rospy.loginfo("Speech is cancelled")
            return
        data = SR.AudioData(msg.data, self.sample_rate, self.sample_width)
        try:
            rospy.loginfo("Waiting for result %d" % len(data.get_raw_data()))
            result = self.recognizer.recognize_google(
                data, language=self.language)
            msg = SpeechRecognitionCandidates(transcript=[result])
            self.pub_speech.publish(msg)
        except SR.UnknownValueError as e:
            rospy.logerr("Failed to recognize: %s" % str(e))
        except SR.RequestError as e:
            rospy.logerr("Failed to recognize: %s" % str(e))