Ticker

6/recent/ticker-posts

Python script that sets up a voice assistant using the SpeechRecognition and pyttsx3 libraries:

 


This script uses the SpeechRecognition library to listen for user input from the microphone, and the pyttsx3 library to speak responses. The speak function takes a string input and uses pyttsx3 to speak the text out loud. The listen function listens for user input and returns it as a lowercase string. If there is an error with the speech recognition service, the function returns an empty string. The script exits the conversation loop if the user says "bye".

import speech_recognition as sr
import pyttsx3

# Set up SpeechRecognition and pyttsx3 instances
r = sr.Recognizer()
engine = pyttsx3.init()

# Define function to speak text
def speak(text):
    engine.say(text)
    engine.runAndWait()

# Define function to listen for user input
def listen():
    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)
        try:
            user_input = r.recognize_google(audio)
            print(f"You said: {user_input}")
            return user_input.lower()
        except sr.UnknownValueError:
            speak("Sorry, I didn't catch that. Can you repeat?")
            return listen()
        except sr.RequestError as e:
            speak("Sorry, there was an error with the speech recognition service. Please try again later.")
            print(f"Speech recognition service error: {e}")
            return ""

# Start voice assistant
speak("Hello, I'm your voice assistant. How can I help you today?")
while True:
    user_input = listen()
    # Exit loop if user says "bye"
    if "bye" in user_input:
        speak("Goodbye!")
        break
    # Otherwise, respond to user input
    speak("I'm sorry, I don't know how to respond to that.")

Post a Comment

0 Comments