Voice Assistant in Python
About the project: This is a simple voice assistant project that can listen to your commands, perform tasks like telling the time, playing music on YouTube, and searching the web, and then respond to you using text-to-speech.
Project Level: AdvanceProject Overview
- The project uses the following Python libraries:
- speech_recognition: To listen to and interpret your voice commands.
- pyttsx3: A cross-platform text-to-speech library to make the assistant speak.
- pywhatkit: To play songs on YouTube.
- wikipedia: To get information from Wikipedia.
- Google Search: To perform general searches.
- pyaudio: A dependency for speech_recognition to handle audio input from the microphone..
Prerequisites
First, you need to install all the required libraries. Open your terminal or command prompt and run the following command:
pip install SpeechRecognition pyttsx3 pywhatkit wikipedia google-search
Note for pyaudio: The pyaudio library can sometimes be difficult to install on certain systems. If you encounter an error, you may need to install it separately. For Windows: Run pip install pipwin and then pipwin install pyaudio. For Linux: Run sudo apt-get install python3-pyaudio or sudo apt-get install portaudio19-dev python-all-dev. For macOS: Run brew install portaudio and then pip install pyaudio.
Project Structure
This project consists of a single Python script. You can name it voice_assistant.py.
The Code (voice_assistant.py)
Copy the following code into your voice_assistant.py file. The code is well-commented to help you understand each part of the voice assistant's functionality.
# voice_assistant.py
import speech_recognition as sr
import pyttsx3
import datetime
import pywhatkit
import wikipedia
import google_search as gs
# Initialize the text-to-speech engine
engine = pyttsx3.init()
voices = engine.getProperty('voices')
# Set a male voice for the assistant
engine.setProperty('voice', voices[0].id)
engine.setProperty('rate', 150) # Set speech rate to a comfortable pace
def speak(text):
"""
Function to make the assistant speak.
"""
print(f"Assistant: {text}")
engine.say(text)
engine.runAndWait()
def listen():
"""
Function to listen for the user's command.
"""
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1 # Pauses for 1 second before stopping listen
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"User: {query}\n")
except Exception as e:
print("Sorry, I didn't get that. Please say again.")
return "None"
return query.lower()
def run_assistant():
"""
Main function to run the assistant and process commands.
"""
speak("Hello, I am your voice assistant. How can I help you today?")
while True:
command = listen()
if 'play' in command:
song = command.replace('play', '')
speak('Playing ' + song)
pywhatkit.playonyt(song)
elif 'search for' in command:
search_query = command.replace('search for', '').strip()
speak(f'Searching the web for {search_query}')
try:
# Use google_search tool to perform the search
search_results = gs.search(queries=[search_query])
# Check if search results are found
if search_results and 'knowledge_graph' in search_results[0] and 'description' in search_results[0]['knowledge_graph']:
description = search_results[0]['knowledge_graph']['description']
speak(f'According to the web, {description}')
elif search_results:
speak("Here is what I found on Google.")
# Open the search results in the browser for a more complete experience
pywhatkit.search(search_query)
else:
speak("Sorry, I could not find any relevant information.")
except Exception as e:
print(f"Error during search: {e}")
speak("I encountered an error while searching. Please try again.")
elif 'wikipedia' in command:
query = command.replace('wikipedia', '').strip()
try:
info = wikipedia.summary(query, sentences=2)
speak("According to Wikipedia...")
speak(info)
except wikipedia.exceptions.PageError:
speak("Sorry, I could not find any information on that topic.")
except Exception as e:
speak("An error occurred. Please try again.")
elif 'time' in command:
current_time = datetime.datetime.now().strftime('%I:%M %p')
speak('Current time is ' + current_time)
elif 'what is your name' in command:
speak("I am a voice assistant created with Python.")
elif 'exit' in command or 'bye' in command or 'goodbye' in command:
speak("Goodbye! Have a great day.")
break
else:
speak("I'm sorry, I don't understand that command. Please try saying it again.")
if __name__ == "__main__":
run_assistant()
How to Run
- Make sure you have installed all the prerequisites as listed above.
- Save the code as voice_assistant.py in your project directory.
- Open your terminal or command prompt and navigate to the directory where you saved the file.
- Run the script using the following command:
python voice_assistant.py
← Back to Projects