Text-to-Speech and Voice Selection in Python
This Python snippet de pyttsx3 library. It allows users to choose between male and female voice options for the speech output. The code also includes basic error handling for user inputs when selecting a voice. A fun way to create a voice assistant named Jarvis!utsavm18
python
6 months ago
2.9 kB
2
Indexable
import pyttsx3 # pip install pyttsx3 for text-to-speech functionality import datetime import speech_recognition as sr # pip install SpeechRecognition for speech recognition functionality engine = pyttsx3.init() def speak(audio): engine.say(audio) engine.runAndWait() def get_voices(): voices = engine.getProperty('voices') try: voice_choice = int(input("Press 1 for male voice\nPress 2 for female voice\n")) if voice_choice == 1: engine.setProperty('voice', voices[0].id) # Male voice elif voice_choice == 2: engine.setProperty('voice', voices[1].id) # Female voice else: print("Invalid choice, defaulting to male voice.") engine.setProperty('voice', voices[0].id) # Default to male except ValueError: print("Invalid input, defaulting to male voice.") engine.setProperty('voice', voices[0].id) # Default to male speak("Hello, this is Jarvis.") def get_time(): Time = datetime.datetime.now().strftime("%I:%M:%S") # hour = I, minutes = M, seconds = S speak("The current time is:") speak(Time) def get_date(): year = int(datetime.datetime.now().year) month = int(datetime.datetime.now().month) day = int(datetime.datetime.now().day) speak("The current date is:") speak(day) speak(month) speak(year) def greeting(): hour = datetime.datetime.now().hour if hour >= 6 and hour < 12: speak("Good morning sir!") elif hour >= 12 and hour < 18: speak("Good afternoon sir!") elif hour >= 18 and hour < 24: speak("Good evening sir!") else: speak("Good night sir!") def wishme(): speak("Welcome back sir!") get_time() get_date() greeting() speak("Jarvis at your service. Please tell me what can I do for you?") def takeCommandCMD(): query = input("Please tell me what can I do for you?\n") return query def takeCommandMic(): r = sr.Recognizer() # Corrected from 'recogniser' to 'Recognizer' with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing...") query = r.recognize_google(audio, language="en-IN") print(query) except Exception as e: print(e) speak("Say that again please...") return "None" return query if __name__ == "__main__": wishme() while True: query = takeCommandMic().lower() if "time" in query: get_time() elif "date" in query: get_date() elif "exit" in query or "quit" in query: # Added exit conditions to stop the loop speak("Goodbye!") break # Exit the while loop
Editor is loading...
Leave a Comment