Skip to content

sharmashubham99/Voice-Assistant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 

Repository files navigation

Voice-Assistant

Simple Python Voice Assistant A foundational, lightweight Voice Assistant built using Python. This project demonstrates basic voice recognition (Speech-to-Text) and audio response (Text-to-Speech) capabilities, allowing a user to interact with the system using simple spoken commands.

-----------------------------------------------------------------------------

Voice Assistant Script

-----------------------------------------------------------------------------

This script creates a simple AI assistant that listens for voice commands

(like "what's the time") and responds by speaking the answer.

PREREQUISITES:

You must install the required Python libraries:

pip install SpeechRecognition pyttsx3

You may also need OS-specific dependencies:

1. Microphone Access (PyAudio):

On Windows: pip install pyaudio

On Linux: sudo apt-get install portaudio19-dev

pip install pyaudio

2. Text-to-Speech Engine (eSpeak/SAPI5):

- On Linux/macOS, pyttsx3 often requires the eSpeak or eSpeak-ng engine.

Linux (Debian/Ubuntu): sudo apt-get install espeak

macOS (Homebrew): brew install espeak

- On Windows, it uses the built-in SAPI5, so usually no extra installation is needed.

-----------------------------------------------------------------------------

import speech_recognition as sr import pyttsx3 import datetime

--- Initialization ---

Initialize the Text-to-Speech engine

SAPI5 is a Microsoft speech API for Windows, commonly used.

If you are on Linux/macOS, pyttsx3 will automatically use a different driver (like eSpeak).

try: engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') # Use the second voice (usually female) if available, otherwise use the default. if len(voices) > 1: engine.setProperty('voice', voices[1].id) engine.setProperty('rate', 170) # Set speaking rate except Exception as e: # If SAPI5 fails (e.g., on Linux, or if eSpeak is not installed) print(f"Warning: Could not initialize TTS engine with SAPI5, falling back to default. Error: {e}") # Try initialization without specifying a driver, hoping it finds a compatible one (like eSpeak) engine = pyttsx3.init() engine.setProperty('rate', 170)

def speak(audio): """Converts the given text to speech.""" print(f"Assistant: {audio}") engine.say(audio) engine.runAndWait()

def listen(): """ Listens to the microphone input and returns the recognized text. Uses the Google Speech Recognition service. """ recognizer = sr.Recognizer() with sr.Microphone() as source: print("Listening...") # Adjust for ambient noise for better recognition recognizer.adjust_for_ambient_noise(source, duration=0.5) # Pause threshold sets the minimum length of silence that ends a phrase recognizer.pause_threshold = 1

    try:
        # Listen to the audio source
        audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
    except sr.WaitTimeoutError:
        print("No speech detected within timeout.")
        return "None"
        
try:
    print("Recognizing...")
    # Use Google's API for speech recognition
    query = recognizer.recognize_google(audio, language='en-US')
    print(f"User said: {query}\n")
    return query.lower()

except sr.UnknownValueError:
    print("Sorry, I could not understand the audio.")
    return "None"
except sr.RequestError as e:
    # Handles issues like no internet connection
    print(f"Could not request results from Google Speech Recognition service; {e}")
    return "None"

def process_command(query): """Processes the recognized text query and provides a spoken response."""

# Simple logic to check for the time command
if 'time' in query:
    now = datetime.datetime.now()
    current_time = now.strftime("%I:%M %p") # e.g., 03:30 PM
    speak(f"The current time is {current_time}.")
    
elif 'hello' in query or 'hi' in query:
    speak("Hello! How can I help you today?")
    
elif 'date' in query:
    now = datetime.datetime.now()
    current_date = now.strftime("%A, %B %d, %Y") # e.g., Monday, October 26, 2024
    speak(f"Today is {current_date}.")
    
elif 'stop' in query or 'exit' in query:
    speak("Goodbye! Have a great day.")
    return True # Signal to exit the loop
    
else:
    # For anything else, you could integrate an LLM API here.
    speak("I am sorry, I can only tell you the time and date right now.")

return False # Signal to continue the loop

--- Main Execution ---

if name == "main": # Start the assistant speak("Starting voice assistant. Please say a command after the beep.")

running = True
while running:
    command = listen()
    
    if command != "none":
        if process_command(command):
            running = False
    else:
        # Optionally stop if too many "None" values occur consecutively
        pass

About

Simple Python Voice Assistant A foundational, lightweight Voice Assistant built using Python. This project demonstrates basic voice recognition (Speech-to-Text) and audio response (Text-to-Speech) capabilities, allowing a user to interact with the system using simple spoken commands.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors