import speech_recognition as sr

# Recognize speech in French
#speech_to_text(language='fr-FR')

# Recognize speech in German
#speech_to_text(language='de-DE')

#def speech_to_text(language='en-US'):
def speech_to_text():
    # Initialize recognizer
    recognizer = sr.Recognizer()

    # Use the microphone as source for input
    with sr.Microphone() as source:
        print("Adjusting for ambient noise... Please wait.")
        recognizer.adjust_for_ambient_noise(source, duration=5)
        print("Listening...")
        
        # Listen for the first phrase and extract it into audio data
        audio_data = recognizer.listen(source, timeout=10, phrase_time_limit=20)

        '''
        timeout: This parameter sets the maximum number of seconds that the listen method will wait for a phrase to start. If this timeout is reached and no speech is detected, it will raise a WaitTimeoutError.
        phrase_time_limit: This parameter sets the maximum number of seconds that the listen method will wait for a phrase to finish. Once this limit is reached, it will stop listening even if the phrase is not finished.
        '''
        
        try:
            # Recognize (convert from speech to text)
            text = recognizer.recognize_google(audio_data)
            print(f"Recognized text: {text}")
        except sr.UnknownValueError:
            print("Sorry, I could not understand the audio.")
        except sr.RequestError:
            print("Could not request results; check your network connection.")

# Example usage
speech_to_text()

