30/06/2024
import speech_recognition as sr
import pyttsx3
# Initialize the speech recognizer and text-to-speech engine
recognizer = sr.Recognizer()
engine = pyttsx3.init()
# Function to speak out text
def speak(text):
engine.say(text)
engine.runAndWait()
# Function to recognize speech
def recognize_speech():
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
# Using Google Web Speech API to recognize speech
command = recognizer.recognize_google(audio)
print(f"Recognized command: {command}")
return command.lower()
except sr.UnknownValueError:
print("Sorry, I didn't get that.")
return ""
except sr.RequestError:
print("Sorry, my speech service is down.")
return ""
# Function to control the device based on voice command
def control_device(command):
if "turn on the light" in command:
# Replace this with actual code to control your device
print("Turning on the light...")
speak("Turning on the light")
elif "turn off the light" in command:
# Replace this with actual code to control your device
print("Turning off the light...")
speak("Turning off the light")
else:
print("Command not recognized.")
# Main function to run the program
if __name__ == "__main__":
speak("Hello! How can I help you?")
while True:
command = recognize_speech()
if command:
control_device(command)
else:
speak("Sorry, could you repeat that?")