AI-powered Voice Assistant Python, C++
👤 Sharing: AI
```python
import speech_recognition as sr
import pyttsx3
import os
import datetime
import webbrowser
import wikipedia
import smtplib
# Initialize speech recognition and text-to-speech engine
recognizer = sr.Recognizer()
engine = pyttsx3.init()
# Set voice properties (optional)
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) # Use female voice (index 1 might work for some systems)
# Set speech rate (optional)
engine.setProperty('rate', 150) # Adjust speed as needed
def speak(text):
"""Speak the given text using the text-to-speech engine."""
engine.say(text)
engine.runAndWait()
def take_command():
"""Listen for user input and return the recognized text."""
with sr.Microphone() as source:
print("Listening...")
recognizer.pause_threshold = 1 # Adjust pause threshold as needed
audio = recognizer.listen(source)
try:
print("Recognizing...")
query = recognizer.recognize_google(audio, language='en-in') # Specify language
print(f"User said: {query}\n")
except sr.UnknownValueError:
print("Sorry, I did not understand. Please repeat.")
return "None"
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service; {e}")
return "None"
return query.lower()
def wish_me():
"""Greet the user based on the time of day."""
hour = int(datetime.datetime.now().hour)
if 0 <= hour < 12:
speak("Good Morning!")
elif 12 <= hour < 18:
speak("Good Afternoon!")
else:
speak("Good Evening!")
speak("I am your AI Assistant. How may I help you?")
def send_email(to, content):
"""Sends an email. You need to configure your email settings securely!"""
# Replace with your actual email address and password/app password
sender_email = "your_email@gmail.com"
sender_password = "your_app_password" # Use an App Password for security
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, to, content)
server.close()
speak("Email has been sent!")
except Exception as e:
print(e)
speak("Sorry, I was unable to send the email.")
if __name__ == "__main__":
wish_me()
while True:
query = take_command()
if query == "none":
continue
elif "wikipedia" in query:
speak("Searching Wikipedia...")
query = query.replace("wikipedia", "")
try:
results = wikipedia.summary(query, sentences=2)
speak("According to Wikipedia:")
print(results)
speak(results)
except wikipedia.exceptions.PageError:
speak("Sorry, I couldn't find that on Wikipedia.")
except wikipedia.exceptions.DisambiguationError as e:
speak("There are multiple results for that query. Please be more specific.")
print(e.options) # Print the options
elif "open youtube" in query:
speak("Opening YouTube...")
webbrowser.open("youtube.com")
elif "open google" in query:
speak("Opening Google...")
webbrowser.open("google.com")
elif "open stackoverflow" in query:
speak("Opening Stack Overflow...")
webbrowser.open("stackoverflow.com")
elif "play music" in query:
music_dir = 'C:\\path\\to\\your\\music\\directory' # Replace with your music directory
try:
songs = os.listdir(music_dir)
if songs: # Check if the directory is not empty
os.startfile(os.path.join(music_dir, songs[0])) # Plays the first song
else:
speak("No music files found in the directory.")
except FileNotFoundError:
speak("The music directory was not found. Please update the path in the code.")
elif "the time" in query:
str_time = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"The time is {str_time}")
elif "open code" in query:
code_path = "C:\\path\\to\\your\\code.exe" # Replace with your IDE or editor path
try:
os.startfile(code_path)
except FileNotFoundError:
speak("The code editor executable was not found. Please update the path in the code.")
elif "send email" in query:
try:
speak("To whom should I send the email?")
to = take_command()
#Basic email validation - IMPROVE THIS!
if "@" not in to or "." not in to:
speak("That doesn't seem like a valid email address. Try again.")
continue #Go back to the beginning of the loop
speak("What should I say?")
content = take_command()
send_email(to, content)
except Exception as e:
print(e)
speak("Sorry, I am unable to send the email.")
elif "exit" in query or "quit" in query or "stop" in query:
speak("Okay, goodbye!")
break
else:
speak("I am sorry, I don't understand that command. Please try again.")
```
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <ctime>
#include <cstdlib> // For system()
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h> // For sleep() on Linux/macOS
#endif
// Placeholder functions (replace with actual implementations)
// These are just stubs to simulate voice assistant functionality
// You would need to use a real TTS (Text-to-Speech) and STT (Speech-to-Text) library
// for actual voice interaction. Examples of TTS libraries: espeak, Festival, SAPI (Windows)
// Examples of STT Libraries: Google Cloud Speech-to-Text API, CMU Sphinx
std::string recognizeSpeech() {
// Simulate speech recognition (replace with actual STT)
// For now, we'll just ask for input from the console
std::string input;
std::cout << "Listening... (Type your command): ";
std::getline(std::cin, input);
return input;
}
void speak(const std::string& text) {
// Simulate speech output (replace with actual TTS)
std::cout << "Assistant: " << text << std::endl;
//Optional: Use a system command to make some kind of sound. Cross-platform is hard.
//This is a very crude example that ONLY works on Linux. Remove it for other platforms.
#ifndef _WIN32
//Beeping with aplay (Linux-only example. Needs 'aplay' command)
std::string command = "aplay -q /usr/share/sounds/alsa/Front_Center.wav"; //Linux only, uses alsa-utils package
system(command.c_str());
#endif
}
std::string getCurrentTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%X", &tstruct); //HH:MM:SS
return buf;
}
void openWebsite(const std::string& url) {
std::string command;
#ifdef _WIN32
command = "start " + url; // Windows
#elif defined(__APPLE__)
command = "open " + url; // macOS
#else
command = "xdg-open " + url; // Linux (using xdg-open)
#endif
int result = system(command.c_str()); // Execute the command
if (result != 0) {
speak("Sorry, I couldn't open the website.");
std::cerr << "Error opening website. System command returned: " << result << std::endl;
}
}
void wishMe() {
time_t now = time(0);
tm* ltm = localtime(&now);
int hour = ltm->tm_hour;
if (hour >= 0 && hour < 12) {
speak("Good morning!");
} else if (hour >= 12 && hour < 18) {
speak("Good afternoon!");
} else {
speak("Good evening!");
}
speak("I am your AI Assistant. How may I help you?");
}
void playMusic() {
//This is a VERY basic, platform-dependent example. It just plays the first MP3 it finds.
//You will need a proper music library integration for real functionality.
#ifdef _WIN32
//Find first MP3 in C:\Music (Windows)
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile("C:\\Music\\*.mp3", &findFileData); // Adjust path as needed
if (hFind != INVALID_HANDLE_VALUE) {
std::string musicPath = "C:\\Music\\" + std::string(findFileData.cFileName); //Path to the music file
FindClose(hFind);
ShellExecute(NULL, "open", musicPath.c_str(), NULL, NULL, SW_SHOWNORMAL);
speak("Playing music.");
} else {
speak("No music found in the specified directory.");
std::cerr << "No music found, or error opening directory.\n";
}
#else
speak("Music playing not implemented on this platform. Requires OS-specific file searching and player control.");
#endif
}
int main() {
wishMe();
while (true) {
std::string query = recognizeSpeech();
if (query.find("hello") != std::string::npos) {
speak("Hello to you too!");
}
else if (query.find("time") != std::string::npos) {
std::string time = getCurrentTime();
speak("The time is " + time);
}
else if (query.find("open youtube") != std::string::npos) {
speak("Opening YouTube.");
openWebsite("https://www.youtube.com");
}
else if (query.find("open google") != std::string::npos) {
speak("Opening Google.");
openWebsite("https://www.google.com");
}
else if (query.find("play music") != std::string::npos) {
playMusic();
}
else if (query.find("exit") != std::string::npos || query.find("quit") != std::string::npos) {
speak("Goodbye!");
break;
}
else {
speak("I'm sorry, I didn't understand that.");
}
}
return 0;
}
```
👁️ Viewed: 8
Comments