My Brief Summer Fling With Siri AI
Back to Tutorials
techTutorialbeginner

My Brief Summer Fling With Siri AI

September 6, 202651 views4 min read

Learn to build a basic voice assistant using Python that can listen to voice commands and respond with spoken answers, similar to Siri AI.

Introduction

In this tutorial, you'll learn how to create a basic voice assistant using Python and the SpeechRecognition library. This hands-on project will teach you the fundamentals of voice recognition and text-to-speech functionality, similar to what powers modern AI assistants like Siri. By the end, you'll have built a simple assistant that can listen to your voice commands and respond with spoken answers.

Prerequisites

To follow this tutorial, you'll need:

  • A computer running Windows, Mac, or Linux
  • Python 3.6 or higher installed
  • Basic understanding of Python programming concepts
  • Microphone access on your computer
  • Internet connection for installing packages

Step-by-step instructions

Step 1: Set up Your Python Environment

First, you need to install the required Python packages. Open your terminal or command prompt and run:

pip install SpeechRecognition pyttsx3

This installs two essential libraries: SpeechRecognition for capturing voice input, and pyttsx3 for converting text to speech. The SpeechRecognition library provides an interface to various speech recognition engines, while pyttsx3 handles text-to-speech conversion on your local machine.

Step 2: Create Your Assistant File

Create a new Python file called voice_assistant.py. This will be your main assistant script. Open it in your preferred code editor and start by importing the necessary libraries:

import speech_recognition as sr
import pyttsx3
import datetime

# Initialize the speech recognizer
recognizer = sr.Recognizer()

# Initialize the text-to-speech engine
engine = pyttsx3.init()

These lines set up the core components of our assistant. The sr.Recognizer() creates an object that can listen to and interpret audio, while pyttsx3.init() prepares the engine to speak.

Step 3: Add Speaking Functionality

Before your assistant can respond to commands, it needs to be able to speak. Add this function to your script:

def speak(text):
    engine.say(text)
    engine.runAndWait()

This function takes any text input and converts it to speech using the pyttsx3 engine. The runAndWait() method ensures the speech finishes before the program continues.

Step 4: Create Voice Recognition Function

Add this function to handle listening for commands:

def listen():
    with sr.Microphone() as source:
        print("Listening...")
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)
    
    try:
        print("Recognizing...")
        command = recognizer.recognize_google(audio)
        print(f"You said: {command}")
        return command.lower()
    except sr.UnknownValueError:
        print("Sorry, I didn't catch that.")
        return ""
    except sr.RequestError:
        print("Sorry, I'm having trouble connecting to the service.")
        return ""

This function uses your computer's microphone to listen for audio. The adjust_for_ambient_noise() helps filter out background noise. If the speech recognition is successful, it returns the recognized text in lowercase for easier processing.

Step 5: Add Command Processing

Now create a function to handle different commands your assistant might receive:

def process_command(command):
    if 'hello' in command:
        speak("Hello there! How can I help you?")
    elif 'time' in command:
        current_time = datetime.datetime.now().strftime("%H:%M")
        speak(f"The current time is {current_time}")
    elif 'goodbye' in command:
        speak("Goodbye! Have a great day!")
        return False
    else:
        speak("I'm sorry, I don't understand that command.")
    return True

This function checks for specific keywords in your voice command and responds appropriately. It returns False when the user says 'goodbye', which will stop the assistant loop.

Step 6: Create the Main Loop

Add the main loop that keeps your assistant running:

def main():
    speak("Voice assistant is now active. Say hello to begin.")
    
    while True:
        command = listen()
        if command:
            if not process_command(command):
                break

if __name__ == "__main__":
    main()

This creates an infinite loop that listens for commands and processes them. When you say 'goodbye', the loop breaks and the program ends.

Step 7: Test Your Assistant

Save your file and run it with:

python voice_assistant.py

When prompted, speak commands like "hello", "what time is it?", or "goodbye". Your assistant should respond with spoken answers. If you encounter issues, make sure your microphone is working and not muted.

Step 8: Enhance Your Assistant

For more advanced functionality, you can add more commands:

elif 'date' in command:
    current_date = datetime.datetime.now().strftime("%B %d, %Y")
    speak(f"Today's date is {current_date}")
elif 'search' in command:
    speak("What would you like me to search for?")
    search_query = listen()
    if search_query:
        speak(f"Searching for {search_query}")

This expands your assistant's capabilities to handle date information and basic search requests.

Summary

In this tutorial, you've built a basic voice assistant using Python that can listen to your voice commands and respond with spoken answers. You learned how to use the SpeechRecognition library for voice input and pyttsx3 for text-to-speech output. This project demonstrates the core concepts behind AI assistants like Siri, showing how simple voice recognition and response systems work. While this assistant is basic, it provides a foundation for more complex voice-controlled applications and helps you understand the technology behind modern voice assistants.

Source: Wired AI

Related Articles