Python Forum
Help Switching between keyboard/Mic input in my code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help Switching between keyboard/Mic input in my code
#1
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 (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()
#------------------------------------------------------------------------------------------
Reply
#2
Both your listener and your GUI want to block the other from running. I don't think you have any choice but to create a thread to run the listener.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Newbie question about switching between files - Python/Pycharm Busby222 3 623 Oct-15-2023, 03:16 PM
Last Post: deanhystad
Question in this code, I input Key_word, it can not find although all data was exact Help me! duchien04x4 3 1,056 Aug-31-2023, 05:36 PM
Last Post: deanhystad
  Code won't break While loop or go back to the input? MrKnd94 2 965 Oct-26-2022, 10:10 AM
Last Post: Larz60+
  Code giving same output no matter the input. Yort 2 2,564 Dec-20-2020, 05:59 AM
Last Post: buran
  I need a code line to spam a keyboard key | Image detection bot Aizou 2 3,136 Dec-06-2020, 10:10 PM
Last Post: Aizou
  Repeating lines of code by an input Josh_Albanos 3 2,427 Oct-15-2020, 01:04 AM
Last Post: deanhystad
  My code is giving my an output of zero, no matter what value I input PiyushBanarjee 1 1,907 Jul-01-2020, 04:34 AM
Last Post: bowlofred
  Hi, I need help with defining user's input and applying it to code. jlmorenoc 2 2,297 Jun-24-2020, 02:10 PM
Last Post: pyzyx3qwerty
  switching from pycharm to sublime issue Drifter 2 2,007 Jun-09-2020, 09:19 PM
Last Post: Drifter
  Keyboard Module Python - Suppress input while writing to window ppel123 0 2,808 Apr-08-2020, 02:51 PM
Last Post: ppel123

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020