Import required libraries
import speech_recognition as sr # For speech-to-text
import pyttsx3 # For text-to-speech
import datetime # For time-related functions
import webbrowser # To open websites
Initialize the text-to-speech engine
engine = pyttsx3.init()
Function to make the assistant speak
def speak(text):
engine.say(text) # Convert text to speech
engine.runAndWait() # Wait until speaking is finished
Function to take voice command from the user
def take_command():
recognizer = sr.Recognizer() # Create a recognizer object
# Use microphone as input sourcewith sr.Microphone() as source: print("Listening...") recognizer.adjust_for_ambient_noise(source) # Reduce background noise audio = recognizer.listen(source) # Capture audiotry: print("Recognizing...") # Convert speech to text using Google API command = recognizer.recognize_google(audio) print("You said:", command)except Exception: # If speech is not recognized speak("Sorry, I didn't catch that.") return ""return command.lower() # Convert command to lowercase
Main function to run the assistant
def run_assistant():
speak(“Hello, I am your voice assistant. How can I help you?”)
while True: command = take_command() # Get user command # Check different commands and respond accordingly if "hello" in command: speak("Hello! How can I assist you?") elif "open google" in command: webbrowser.open("https://www.google.com") speak("Opening Google") elif "open youtube" in command: webbrowser.open("https://www.youtube.com") speak("Opening YouTube") elif "time" in command: # Get current system time current_time = datetime.datetime.now().strftime("%I:%M %p") speak(f"The time is {current_time}") elif "exit" in command or "stop" in command: speak("Goodbye!") break # If command is not recognized but not empty elif command != "": speak("Sorry, I don't understand that command.")
Run the assistant when the script is executed
if name == “main“:
run_assistant()
Leave a Reply
You must be logged in to post a comment.