title: Threading: Listen and recognize my speech while performing other tasks in the background
body: <p>I am trying to build my personal voice assistant. The thing that I find difficult is when my program has recognized my speech and doing the thing it's supposed to do when it hears a key word — it just stops listening. Other functions are still working, except for the speech recognition.</p>
  <pre><code>import random
  import time
  import datetime
  import speech_recognition as sr
  import pyttsx3
  from threading import Thread
  import pyaudio
  
  engine = pyttsx3.init()
  engine.setProperty(&quot;rate&quot;, 165)
  voices = engine.getProperty(&quot;voices&quot;)
  engine.setProperty(&quot;voice&quot;, voices[1].id)
  
  threadlist = []
          
  def listening():
      while 2 == 2:
          try:
              with sr.Microphone() as source:
                  r = sr.Recognizer()
                  print(&quot;start listening&quot;)
                  audio_data = r.listen(source)
                  print(&quot;Recognizing...&quot;)
                  global sentence
                  text = r.recognize_google(audio_data, language=&quot;us-US&quot;)
                  sentence = text.lower()
                  print(sentence)
                  if &quot;time&quot; in sentence.split():
                      print(&quot;said time&quot;)
                      engine.say(f&quot;Right now it is {current_hour} hours and {current_minute} minutes&quot;)
                      engine.runAndWait()
                  elif &quot;thank&quot; in sentence.split():
                      if &quot;you&quot; in sentence.split():
                          engine.say(&quot;You are welcome, sir&quot;)
                          engine.runAndWait()
          except:
              print(&quot;Failed to recognize the sound&quot;)
              text = &quot;&quot;               
  
  
  def get_datetime():
      while 2 == 2:
          global current_hour
          global current_minute
          global current_day
          print(&quot;getting datetime&quot;)
          current_datetime = datetime.datetime.now()
  
          current_hour = current_datetime.strftime(&quot;%H&quot;)
          current_minute = current_datetime.strftime(&quot;%M&quot;) 
          current_day = current_datetime.strftime(&quot;%u&quot;) 
          time.sleep(30)
  
  def test():
      i = 0
      while i &lt; 50:
          i = i + 1
          time.sleep(2)
          print(i)
  
  threadlist.append(Thread(target=get_datetime))
  threadlist.append(Thread(target=listening))
  threadlist.append(Thread(target=test))
  
  for t in threadlist:
      t.start()
  for t in threadlist:
      t.join()
  </code></pre>