Categories We Write About

Create a voice-activated assistant

Creating a voice-activated assistant involves integrating speech recognition, natural language processing, and speech synthesis. Here’s a clear, step-by-step guide to build a simple voice assistant using Python with popular libraries like SpeechRecognition, pyttsx3 for text-to-speech, and some basic command handling.


Step 1: Install Required Libraries

bash
pip install SpeechRecognition pyttsx3 pyaudio

Note: On some systems, installing pyaudio might require extra steps or system-specific packages.


Step 2: Basic Voice Assistant Code

python
import speech_recognition as sr import pyttsx3 # Initialize recognizer and TTS engine recognizer = sr.Recognizer() tts_engine = pyttsx3.init() def speak(text): tts_engine.say(text) tts_engine.runAndWait() def listen(): with sr.Microphone() as source: print("Listening...") recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) try: command = recognizer.recognize_google(audio) print(f"You said: {command}") return command.lower() except sr.UnknownValueError: speak("Sorry, I did not understand that.") return "" except sr.RequestError: speak("Sorry, my speech service is down.") return "" def process_command(command): if 'hello' in command: speak("Hello! How can I assist you today?") elif 'time' in command: from datetime import datetime now = datetime.now().strftime("%H:%M") speak(f"The current time is {now}") elif 'exit' in command or 'quit' in command: speak("Goodbye!") return False else: speak("Sorry, I can't do that yet.") return True def main(): speak("Voice assistant activated. Say something.") running = True while running: command = listen() if command: running = process_command(command) if __name__ == "__main__": main()

How It Works

  • The program listens to your voice input via the microphone.

  • Converts speech to text using Google’s Speech Recognition API.

  • Processes simple commands like greetings, checking the time, or exiting.

  • Responds with spoken feedback.


How to Expand

  • Add more commands (e.g., weather, web search, controlling apps).

  • Integrate with APIs (Google, OpenWeather, Wikipedia).

  • Use NLP libraries like spaCy or transformers for better understanding.

  • Implement wake word detection for hands-free activation.


Would you like me to help you create a more advanced voice assistant or integrate specific features?

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About