Use Python Code to connect to mic by using module, give input to mic and either it will print the text or run the command.
To accomplish this task, we can use the speech_recognition module in Python to capture audio from the microphone and the os module to execute commands. First, you need to install the speech_recognition module if you haven’t already. You can install it using pip:
pip install SpeechRecognition
Next, we'll create a Python script that listens to the microphone input, converts it to text using speech recognition, and then either prints the text or runs the command if the input matches a predefined keyword.
Here's the Python code:
import speech_recognition as sr
import os
# Function to convert speech to text
def speech_to_text():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
text = recognizer.recognize_google(audio)
return text.lower()
except sr.UnknownValueError:
print("Sorry, could not understand audio.")
except sr.RequestError as e:
print(f"Error with the speech recognition service; {e}")
return None
# Main function to handle user input and commands
def main():
while True:
input_text = speech_to_text()
if input_text:
print("You said:", input_text)
if input_text == "quit":
print("Exiting the program...")
break
else:
# Check for predefined commands here
if input_text == "run calculator":
os.system("calc") # Run calculator on Windows
elif input_text == "open browser":
os.system("start \"\" https://www.google.com") # Open browser on Windows
elif input_text == "open terminal":
os.system("gnome-terminal &") # Open terminal on Linux (for example, using GNOME)
# Add more commands as needed
if __name__ == "__main__":
main()
Please note that this code is a simple example, and you can extend it to add more commands and customize it according to your needs. Make sure you have a working microphone connected to your computer, and you can modify the predefined commands to execute different actions based on the user’s voice input.
Thanks for @vimaldagasir for approaching me.