Not answering for a long time. speech_recognition

Question:

So i have this code that will listen to you speech recognition and and answer using pyttsx3 and openai but the problem is speech_recognition gets everything right but it will give errors if i say gibberish or just mute.

can please help me. me no English

code:

import speech_recognition as sr
import pyttsx3
import openai
import random
openai.api_key=('API KEY')
l=sr.Recognizer()
working=True
while working== True:
    print('listening...')
    with sr.Microphone() as source:
        voice = l.listen(source)
        command = l.recognize_google(voice)
        print(command)
        r = openai.Completion.create(
            engine='text-curie-001',
            prompt=command,
            temperature=0.41,
            max_tokens=64
        )
        print(r.choices[0].text)
        engine = pyttsx3.init()
        engine.say(r.choices[0].text)
        engine.runAndWait()
    engine = pyttsx3.init()
    engine.runAndWait()
Asked By: COOL

||

Answers:

Try this:

#C:UserskeibodPycharmProjectsspeech_recognition
import speech_recognition as sr
import pyttsx3
import openai
import random
openai.api_key=('API KEY')
l=sr.Recognizer()
working=True
while working== True:
    print('listening...')
    try:
        with sr.Microphone() as source:
            voice = l.listen(source)
            command = l.recognize_google(voice)
            print(command)
            r = openai.Completion.create(
                engine='text-curie-001',
                prompt=command,
                temperature=0.41,
                max_tokens=64
            )
            print(r.choices[0].text)
            engine = pyttsx3.init()
            # say method on the engine that passing input text to be spoken
            engine.say(r.choices[0].text)
            # run and wait method, it processes the voice commands
            engine.runAndWait()
    except:
        engine = pyttsx3.init()
        texts=['Please try saying that again','I dont understand', 'Could you try saying that again','what!', 'bruh talk propely','may you please learn english and come back','ratioed ']
        text=random.choices(texts)
        print(text)
        engine.say(text)
        # run and wait method, it processes the voice commands
        engine.runAndWait()
Answered By: kevinjonson133