Aug-28-2022, 08:58 PM
Hello,
I'm trying to get my voice assistant to be able to take user commands via Keyboard or Mic depending on what the user chooses.
Right now, it defaults to keyboard input (
The problem I have is that I don't know how to hold the setting for Mic Input because as soon as the user says a command with the mic it will do it's thing, then immediately default back to the keyboard input.
How can I have it so if the user switches to Mic Input
Thanks in advance.
Code Snippet:
I'm trying to get my voice assistant to be able to take user commands via Keyboard or Mic depending on what the user chooses.
Right now, it defaults to keyboard input (
command = UserInput()
) but I would like it to switch to Mic input (Command = listen()
) if the user presses (M) or enters: 'Switch to Mic'.The problem I have is that I don't know how to hold the setting for Mic Input because as soon as the user says a command with the mic it will do it's thing, then immediately default back to the keyboard input.
How can I have it so if the user switches to Mic Input
command = listen()
it will stay like that until the user switches back to keyboard input? Thanks in advance.
Code Snippet:
#------------------------------------------------------------------------------------- # User Input Function #------------------------------------------------------------------------------------- def UserInput(): command = str(Prompt.ask("[yellow]Commander[/yellow]")) # CommanderInput(command) return command #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Listen Function #------------------------------------------------------------------------------------- def listen(): hear = sr.Recognizer() with sr.Microphone() as source: #---------------------- #Auto typing animation: results = "Listening..." print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- audio = hear.listen(source) #--------------------------- # Uses google API to listen try: #---------------------- #Auto typing animation: results = "Recognizing..." print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- command = hear.recognize_google(audio, language='en-in') print("[yellow]Commander: " + command) #-------------------------------- except: pass return command #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Startup Function #------------------------------------------------------------------------------------- def StartupText(): #---------------------- #Auto typing animation: results = """ Starting Systems... Systems Started... Defaulting to Keyboard Input... [To Switch Between Keyboard & Mic Input, Press (K) to use Keybaord Press (M) to use Mic When Prompted or Input: 'Switch to Keyboard' for Keyboard 'Switch to Mic' fo Mic] """ print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Main #------------------------------------------------------------------------------------- def BAXTER(): command = UserInput() # Default to keyboard Input command=str(command).lower() #------------------------------------------------------------------------------------- # Switch between Keyboard and Mic Input #------------------------------------------------------------------------------------- if ('K' in command) or ('switch to keyboard' in command): command = UserInput() elif ('M' in command) or ('switch to mic' in command): command = listen() #------------------------------------------------------------------------------------- #Search Wikipedia (General Info) #------------------------------------------------------------------------------------- if ('weather' not in command): if ('who is' in command) or ('what is the' in command) or ('what is a' in command) or ("what is" in command): if ('time' not in command): if ('news' not in command): speak('Searching Wikipedia...') command = command.replace("who is","") command = command.replace("what is the","") command = command.replace("what is a","") command = command.replace("what is","") results = wikipedia.summary(command, sentences = 2) #---------------------- #Auto typing animation: print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- speak(results)Full Code:
#!/usr/bin/env python3 #------------------------------------------------------------------------------------- # B.A.X.T.E.R A.I System #------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------- # Table Of Contents/Overview #---------------------------------------------------------------------------------------------- # Imports # Commander & A.I Name # Voice Settings # Header Output # User Input Function # Listen Function # WishMe Function # Main # - General Conversation # -- Search Wikipedia # --- Search Wolfram Alpha # ---- Open Stuff on Internet # ----- Open Stuff on Computer # ------ Stop Program # Run Program #---------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Imports #------------------------------------------------------------------------------------- import json import random import datetime import operator import os import subprocess import time import sys import webbrowser import requests from bs4 import BeautifulSoup import wikipedia import wolframalpha import pyttsx3 import speech_recognition as sr import pywhatkit from Intents import greetings, farewell from rich import print from rich.panel import Panel from rich.text import Text from rich.prompt import Prompt from rich.console import Console #------------------------------------------------------------------------------------- #Commander Name (You) and A.I Name #------------------------------------------------------------------------------------- Commander = "Commander" AI_Name = 'Baxter' #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Voice Settings #------------------------------------------------------------------------------------- def speak(audio): speaker = pyttsx3.init () voices = speaker.getProperty('voices') speaker.setProperty('voice',voices[2].id) speaker.setProperty ('rate', 180) speaker.say (audio) speaker.runAndWait () # # Test to see all avaliable voices # engine = pyttsx3.init() # voices = engine.getProperty('voices') # for voice in voices: # print(voice, voice.id) # engine.setProperty('voice', voice.id) # engine.say("Hello World!") # engine.runAndWait() # engine.stop() #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Header Display Function #------------------------------------------------------------------------------------- def header(): console = Console(width=100) style = "bold green on blue" console.print("[green]B.A.X.T.E.R A.I System", style=style, justify="center") #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # User Input Function #------------------------------------------------------------------------------------- def UserInput(): command = str(Prompt.ask("[yellow]Commander[/yellow]")) # CommanderInput(command) return command #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Listen Function #------------------------------------------------------------------------------------- def listen(): hear = sr.Recognizer() with sr.Microphone() as source: #---------------------- #Auto typing animation: results = "Listening..." print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- audio = hear.listen(source) #--------------------------- # Uses google API to listen try: #---------------------- #Auto typing animation: results = "Recognizing..." print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- command = hear.recognize_google(audio, language='en-in') print("[yellow]Commander: " + command) #-------------------------------- except: pass return command #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Startup Function #------------------------------------------------------------------------------------- def StartupText(): #---------------------- #Auto typing animation: results = """ Starting Systems... Systems Started... Defaulting to Keyboard Input... [To Switch Between Keyboard & Mic Input, Press (K) to use Keybaord Press (M) to use Mic When Prompted or Input: 'Switch to Keyboard' for Keyboard 'Switch to Mic' fo Mic] """ print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # WishMe Function #------------------------------------------------------------------------------------- def wishMe(): hour = int(datetime.datetime.now().hour) if hour>=0 and hour<12: speak("Good Morning" + Commander) elif hour>=12 and hour<18: speak("Good Afternoon" + Commander) else: speak("Good Evening" + Commander) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Main #------------------------------------------------------------------------------------- def BAXTER(): command = UserInput() command=str(command).lower() #------------------------------------------------------------------------------------- # Switch between Keyboard and Mic Input #------------------------------------------------------------------------------------- if ('K' in command) or ('switch to keyboard' in command): command = UserInput() elif ('M' in command) or ('switch to mic' in command): command = listen() #------------------------------------------------------------------------------------- # General Conversation (From Intents.py) #------------------------------------------------------------------------------------- #Greetings patterns, responses = greetings() if (command in patterns): response = (random.choice(responses)) #---------------------- #Auto typing animation: print("[green]Baxter: [/green]", end="") for i in response: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.1) print("\n") #---------------------- speak(response) #Farewell patterns, responses = farewell() if (command in patterns): response = (random.choice(responses)) #---------------------- #Auto typing animation: print("[green]Baxter: [/green]", end="") for i in response: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.1) print("\n") #---------------------- speak(response) #------------------------------------------------------------------------------------- #Search Wikipedia (General Info) #------------------------------------------------------------------------------------- if ('weather' not in command): if ('who is' in command) or ('what is the' in command) or ('what is a' in command) or ("what is" in command): if ('time' not in command): if ('news' not in command): speak('Searching Wikipedia...') command = command.replace("who is","") command = command.replace("what is the","") command = command.replace("what is a","") command = command.replace("what is","") results = wikipedia.summary(command, sentences = 2) #---------------------- #Auto typing animation: print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- speak(results) #------------------------------------------------------------------------------------- #Search Wolfram Alpha (Math/Conversions, Definitions) #------------------------------------------------------------------------------------- if ('weather' not in command): if ('news' not in command): if ('calculate' in command) or ("what's" in command) or ('define' in command): speak('Searching Wolfram Alpha...') command = command.replace("calculate","") command = command.replace("what's","") command = command.replace("define","") # Wolframalpha App Id appId = 'JH9XHR-W9J76L7H5A' # Wolfram Instance client = wolframalpha.Client(appId) res = client.query(''.join(command)) results = next(res.results).text #---------------------- #Auto typing animation: print("[green]Baxter: [/green]", end="") for i in results: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.05) print("\n") #---------------------- speak(results) #------------------------------------------------------------------------------------- #Open Stuff on the Internet #------------------------------------------------------------------------------------- #Open Youtube Videos (Ex: 'Play __ on youtube') if ('youtube' in command): speak('Launching Youtube') command = command.replace("youtube","") pywhatkit.playonyt(command) #Open Google Maps and Find The Location of A You Want if ('where is' in command): command = command.replace("where is","") speak('Locating' + command) webbrowser.open_new_tab("https://www.google.com/maps/place/" + command) #Search Stuff on Google if ('search' in command): command = command.replace("search", "") speak('Searching' + command) pywhatkit.search(command) #Close Firefox if ('close firefox' in command): speak('Closing Firefox') command = command.replace("close firefox", "") browser = "firefox.exe" os.system("taskkill /f /im " + browser) #------------------------------------------------------------------------------------- #Open Stuff on the Computer #------------------------------------------------------------------------------------- #Open Windows Media Player and Auto Play the Playlist Called Music if ('play music' in command) or ('media player' in command) or ('drop the needle' in command): speak('Launching Music') command = command.replace("play music", "") command = command.replace("media player", "") command = command.replace("drop the needle", "") subprocess.Popen("C:\Program Files (x86)\Windows Media Player\wmplayer.exe /Playlist Music") #Close Windows Media Player if ('stop music' in command): speak('Closing Music') command = command.replace("stop music", "") mediaPlayer = "wmplayer.exe" os.system("taskkill /f /im " + mediaPlayer) #------------------------------------------------------------------------------------- #Stop Program/Script Command #------------------------------------------------------------------------------------- if ('stop' in command) or ('shutdown' in command) or ('quit' in command): speak("Shutting Down...") response = "Terminating program..." #---------------------- #Auto typing animation: print("[green]Baxter: [/green]", end="") for i in response: sys.stdout.write(i) sys.stdout.flush() time.sleep(0.1) print("\n") #---------------------- exit() #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------ # Run The Program #------------------------------------------------------------------------------------------ header() StartupText() wishMe() speak("How may I be of service?") while True: BAXTER() #------------------------------------------------------------------------------------------