Example #1
0
def recognize(source):
    r = Recognizer()
    source.stream.start_stream()
    audio = r.listen(source)
    source.stream.stop_stream()
    vprint(4, "Finished recording.")
    try:
        vprint(0, "You said " + r.recognize(audio))
    except LookupError:
        vprint(0, "Could not understand audio")
Example #2
0
from speech_recognition import Recognizer, Microphone

if __name__ == '__main__':

    print("----------------")
    print("INITIALIZING THE CLIENT...")
    client = Recognizer()
    print(type(client))

    print("----------------")
    print("HELLO! I AM LISTENING. WHEN YOU ARE READY, PLEASE SAY SOMETHING... ")
    with Microphone() as mic:
        audio = client.listen(mic)

    print("AUDIO CAPTURED. ANALYZING...")
    #transcript = client.recognize_google(audio)
    response = client.recognize_google(audio, show_all=True) # passing show_all gets us the confidence and alternatives
    best_alternative = response["alternative"][0]
    transcript = best_alternative["transcript"]
    #confidence = best_alternative["confidence"]

    print("----------------")
    print("RESULTS:")
    print(f"\n    '{transcript.upper()}'")
    print("\n    ", response, "\n")
Example #3
0
r = Recognizer()
m = None
input_mic = 'Scarlett 2i4 USB'  # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
    if microphone_name == input_mic:
        m = Microphone(device_index=i)

while True:
    """
    Commands will be entered in the specific format explained here:
     - the first word will be one of: 'album', 'artist', 'play'
     - then the name of whatever item is wanted
    """
    with m as source:
        r.adjust_for_ambient_noise(source=source)
        audio = r.listen(source=source)

    command = None
    try:
        command = r.recognize_google(audio_data=audio).lower()
    except UnknownValueError:
        continue

    print(command)
    words = command.split()
    if len(words) <= 1:
        print('Could not understand. Try again')
        continue

    name = ' '.join(words[1:])
    try:
Example #4
0
from speech_recognition import Microphone as Mic
from speech_recognition import Recognizer as r
import pyaudio

with Mic():
    print("say something")
    audio = r.listen(Mic)
    print("time over thanks")

try:
    print("Text : " + r.recognize_google(audio))
except:
    print("Sorry i couldn't hear you")
Example #5
0
from speech_recognition import Recognizer, Microphone

r = Recognizer()

with Microphone() as src:
    print("Speak...")
    audio = r.listen(src)
    txt = r.recognize_google(audio, language='pt-br')
    print(txt)
Example #6
0
class Speech(object):
    def __init__(self):
        rospy.init_node("speech")
        self.pub = rospy.Publisher("speech_recognizer",
                                   String,
                                   latch=True,
                                   queue_size=1)
        self.recognizer = Recognizer()
        # self.recognizer.energy_threshold = 1000
        # self.recognizer.pause_threshold = .7
        self.microphone = Microphone()

    @staticmethod
    def check_internet_connection():
        connection = httplib2.HTTPConnectionWithTimeout("www.google.com",
                                                        timeout=5)
        try:
            connection.request("HEAD", "/")
            connection.close()
            return True
        except httplib2.HttpLib2Error:
            connection.close()
            return False

    def __recognize_helper(self, recognized_speech):
        '''
        Once speech obtained do TODO:something with it
        '''
        print(recognized_speech)
        if recognized_speech != "":
            rospy.loginfo("You said: " + recognized_speech)
            self.pub.publish(recognized_speech)

    def __microphone_helper(self, ):
        rospy.loginfo('Listening...')
        with self.microphone as source:
            # If phase_time_limit is not set to 5 it will
            # take a really long time every 3-4th attempt
            audio = self.recognizer.listen(source, phrase_time_limit=5)
        rospy.loginfo('Got a sound; recognizing...')
        return audio

    def recognize_google(self):
        with self.microphone as source:
            self.recognizer.adjust_for_ambient_noise(source)

        try:
            while not rospy.is_shutdown():
                audio = self.__microphone_helper()
                recognized_speech = ""
                if Speech.check_internet_connection():
                    try:
                        recognized_speech = self.recognizer.recognize_google(
                            audio)
                    except sr.UnknownValueError:
                        rospy.logerr("Could not understand audio.")
                    except sr.RequestError:
                        rospy.logerr("Could not request results.")
                else:
                    rospy.logerr("No internet conneciton for Google API")

                self.__recognize_helper(recognized_speech)

        except Exception as exc:
            rospy.logerr(exc)

    def recognize_sphynix(self):
        with self.microphone as source:
            self.recognizer.adjust_for_ambient_noise(source)
        try:
            while not rospy.is_shutdown():
                audio = self.__microphone_helper()
                recognized_speech = ""

                try:
                    recognized_speech = self.recognizer.recognize_sphinx(audio)
                except sr.UnknownValueError:
                    rospy.logerr("Could not understand audio.")
                except sr.RequestError:
                    rospy.logerr("""Could not request results. Do you have
                     pocket Sphynx installed?""")
                self.__recognize_helper(recognized_speech)
        except Exception as exc:
            rospy.logerr(exc)
Example #7
0
class SpeechRecognition(Thread):
    def __init__(self):
        Thread.__init__(self, daemon=True);
        self.rec = Recognizer();
        self.rec.energy_threshold=110;
        self.rec.pause_threshold=0.5;
        self.rec.operation_timeout=5;
        self.mic = Microphone(device_index = 2);
        self.answer = AnswerBot('de.txt');
    def command(self, command, said):
        global render_mode;
        command = command.split(" ");
        if command[0]=='time':
            render_mode = 'time';
            yield str(current_time.hour) + "Uhr und " + str(current_time.minute) + " minuten.";
        elif command[0]=='shutdown':
            exit(True);
        elif command[0]=='restart':
            exit(False); 
        elif command[0]=='wiki':
            search = said.lower().split(command[1].replace('_', ' '))[1].lower();
            setAlert('Suche: "' + search + '"');
            say("Suche nach " + search);
            result = wikipedia.summary(search);
            split = result.split('.');
            if len(split)>4:
                result = '';
                for i in range(0,4):
                    result += split[i] + '.';
            yield result;
        elif command[0]=='weather':
            global weather;
            if command[1] == 'today':
                yield "Hier ist die aktuelle Wetterlage.";
                weather = weathersystem.getCurrentWeather();
            elif command[1] == 'tomorrow':
                yield "Hier ist die vorrausichtliche Wetterlage.";
                weather = weathersystem.getWeatherTomorrow();
            render_mode = 'weather';
            yield 'Temperatur: ' + str(weather['temperature']) + '°C';
            yield 'Luftfeuchtigkeit: ' + str(weather['humidity']) + '%';
            yield 'Wind: ' + str(weather['wind']) + 'km/h';
            yield 'Bewölkung: ' + str(weather['clouds']) + '%';                
    def out(self, pMessage):
        setAlert('"' + pMessage + '"');
        print("Heard: " + pMessage);
        response = self.answer.find_answer(pMessage);
        print("Response: ",response);
        if response[0]!=None:
             if response[0][0]=='>':
                 for entry in self.command(response[0][1:], pMessage):
                     say(entry);
             else:
                 say(response[0]);
    def listen(self, audio):
        self.out(self.rec.recognize_google(audio, language='de-DE'));
    def initialize(self):
        with self.mic as source:
            self.rec.listen_in_background(source, self.listen);
    def run(self):
        while True:
            try:
                with self.mic as source:
                     audio = self.rec.listen(source, timeout=None);
                     self.out(self.rec.recognize_google(audio, language='de-DE'));
            except Exception as e:
                 print(e);
Example #8
0
import speech_recognition
from speech_recognition import Recognizer

speech_recognizer = Recognizer()

with speech_recognition.Microphone() as source:
    audio = speech_recognizer.listen(source)

    try:
        text = speech_recognizer.recognize_google(audio)
        print(text)
    except:
        pass
Example #9
0
def ask(r: sr.Recognizer, source: sr.AudioSource, message: str = None):
    if message:
        speak(message)

    audio = r.listen(source)
    return r.recognize_google(audio, language="pt-BR")
Example #10
0
#!/bin/python3
from speech_recognition import Microphone, Recognizer, UnknownValueError

recognizer = Recognizer()

# On enregistre le son

with Microphone() as source:
    print("Réglage du bruit ambiant... Patientez...")
    recognizer.adjust_for_ambient_noise(source)
    print("Vous pouvez parler...")
    recorded_audio = recognizer.listen(source)
    print("Enregistrement terminé !")
    with open("record.wav", "wb") as f:
        f.write(recorded_audio.get_wav_data())
# Reconnaissance de l'audio

try:
    print("Reconnaissance du texte...")
    googletext = recognizer.recognize_google(recorded_audio, language="fr-FR")
    print("Google pense que vous avez dit {}".format(googletext))
except UnknownValueError:
    print("L'audio n'as pas été compris par Google")
except Exception as ex:
    print(ex)

try:
    print("Reconnaissance du texte...")
    sphinxtext = recognizer.recognize_sphinx(recorded_audio, language="fr-FR")
    print("Sphinx pense que vous avez dit {}".format(sphinxtext))
except UnknownValueError: