27 – Real-World Python Projects – Voice Assistant

🎯 Project Objective

To create a Python-based voice-controlled assistant that listens to commands, performs actions (like searching the web or opening apps), and speaks responses aloud.


🧩 1. What You’ll Learn

  • 🎀 Capturing voice input using speech_recognition
  • πŸ”Š Making Python speak with pyttsx3
  • 🌐 Performing tasks like opening YouTube, searching Google, checking time, etc.
  • βš™οΈ Handling multiple commands with simple AI logic

βš™οΈ 2. Required Libraries

We’ll auto-install them within the code πŸ‘‡

# Auto install required modules
import os
import sys
import subprocess

def install(pkg):
    subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])

for pkg in ["speechrecognition", "pyttsx3", "pyaudio"]:
    try:
        __import__(pkg)
    except ImportError:
        install(pkg)

πŸŽ™οΈ 3. Main Voice Assistant Code

import speech_recognition as sr
import pyttsx3
import datetime
import webbrowser
import os
import subprocess

# Initialize the text-to-speech engine
engine = pyttsx3.init()
engine.setProperty('rate', 175)  # Speaking speed
engine.setProperty('volume', 1.0)

def speak(text):
    print(f"Assistant 🎧: {text}")
    engine.say(text)
    engine.runAndWait()

def listen():
    r = sr.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(f"You said: {query}\n")
    except Exception:
        speak("Sorry, I didn't catch that.")
        return ""
    return query.lower()

def greet_user():
    hour = int(datetime.datetime.now().hour)
    if hour < 12:
        speak("Good morning! I'm your Python Assistant.")
    elif hour < 18:
        speak("Good afternoon!")
    else:
        speak("Good evening!")
    speak("How can I help you today?")

🧩 4. Performing Real-World Actions

def perform_task(query):
    if "time" in query:
        time = datetime.datetime.now().strftime("%I:%M %p")
        speak(f"The time is {time}")

    elif "date" in query:
        date = datetime.datetime.now().strftime("%A, %d %B %Y")
        speak(f"Today is {date}")

    elif "open youtube" in query:
        speak("Opening YouTube...")
        webbrowser.open("https://www.youtube.com")

    elif "open google" in query:
        speak("Opening Google...")
        webbrowser.open("https://www.google.com")

    elif "search" in query:
        speak("What should I search for?")
        term = listen()
        if term:
            url = f"https://www.google.com/search?q={term}"
            speak(f"Searching for {term}")
            webbrowser.open(url)

    elif "play music" in query:
        music_dir = "C:\\Users\\Public\\Music"  # change path if needed
        songs = os.listdir(music_dir)
        if songs:
            speak("Playing music...")
            os.startfile(os.path.join(music_dir, songs[0]))
        else:
            speak("No music files found.")

    elif "shutdown" in query:
        speak("Shutting down the system. Goodbye!")
        os.system("shutdown /s /t 5")

    elif "exit" in query or "quit" in query or "stop" in query:
        speak("Goodbye! Have a great day.")
        exit()

    else:
        speak("Sorry, I didn’t understand that command.")

🧭 5. Main Loop

if __name__ == "__main__":
    greet_user()
    while True:
        command = listen()
        if command:
            perform_task(command)

🧠 6. How It Works

StepAction
🎀 ListenCaptures your voice using speech_recognition
🧠 RecognizeConverts speech β†’ text via Google API
βš™οΈ ProcessMatches text with available commands
πŸ”Š SpeakResponds using pyttsx3 speech engine
πŸ’» ExecuteOpens browser, plays music, etc.

πŸ’‘ 7. Add More Commands

You can extend it easily:

elif "open notepad" in query:
    speak("Opening Notepad...")
    os.system("notepad")

elif "send email" in query:
    speak("Feature not yet implemented, but we can add SMTP support later.")

πŸ” 8. Enhancement Ideas

FeatureDescription
🧩 Custom Wake WordActivate only when user says β€œHey Python”
πŸ’¬ ChatGPT IntegrationConnect to GPT API for intelligent replies
🏠 Smart HomeControl IoT devices using HTTP/MQTT APIs
🧾 RemindersAdd daily reminder or notes feature
🌀️ Weather ReportsIntegrate OpenWeather API
🎡 Spotify ControlUse spotipy library to control Spotify
πŸ“± Mobile IntegrationUse Flask API to connect with your phone

βœ… Summary

FeatureDescription
🎀 Voice RecognitionConverts speech to text
πŸ”Š Text-to-SpeechSpeaks responses aloud
🌐 Smart ActionsOpens sites, apps, searches online
βš™οΈ CustomizableEasy to add your own commands
πŸ’‘ ScalableCan become your personal AI assistant

Comments

Leave a Reply

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