SOLVED: Python and while loop

Hi,

I’m quite new to touchdesigner and have a question about using a python while loop.

I have two Text Dat’s: ‘listen’ and ‘prompt’.
Listen contains a python script that continuously listens to a microon and once the word ‘stop’ is said it has to send the spoken text to the text-dat ‘prompt’. Then the script has to continue and as soon as the word ‘stop’ is said again, the text-dat ‘prompt’ is emptied and the new spoken text is put in ‘prompt’, etc…
When ‘end’ is said, the script stops.

The script is below.

I am unable to get this working. The spoken-text is written to the text-dat prompt only when the script is finished, but not during the while loop. And during the while loop also the timeline paused, so other processes are waiting on the while loop.
This also applies if, for example, I want to send a trigger to another component within the while loop.
How can I solve this?

The script in the ‘Listen’ text-dat (in abbreviated form and without the right indentations):

import speech_recognition as sr
r = sr.Recognizer()
microphone = sr.Microphone()
phrase = ""
prompt = on('prompt')
prompt.clear()
whileTrue:
   with microphone as source:
      audio = r.listen(source, phrase_time_limit=60)
   try:
      speak = r.recognize_google(audio, language="en-US")
      if "stop" in speak.lower():
         sentence += speak.lower().replace("stop", "") + " "
         prompt.clear()
         prompt.write(sentence)
         speak = ""
         sentence = ""
         continuous
      elif "end" in speak.lower():
         break
   except sr.UnknownValueError:
         #do some error handling and continue
          continuous
   except sr.RequestError as e:
         #do some error handling and break
         break

Sincerely, Pieter van Dijk

Hey @pietervandyk,

a while True: python loop in TouchDesigner in this context would cause the application to hang as it waits for the script to finish executing. Python is blocking the frame.
A workaround might be using python’s treading library following examples provided by @raganmd here: GitHub - raganmd/touchdesigner-multi-threading: A look at how to use multiple threads in python with TouchDesigner or most simple might be actually running a python app in parallel and sending the results to TouchDesigner via UDP, OSC or similar.

cheers
Markus

Instead of using a while loop in a python script put that code in a Execute DAT in the Frame_Start function. You could also keep all your code in the python script but break the while loop into a function and just call that function on the Execute DAT Frame_Start function.

Hey :slight_smile: I have the same issue here and I am really struggeling because I don’t know python. I wrote this simple code:
my = op( ‘constant8’ )[ ‘chan1’ ]

if my == 1:
op(‘geo4’).allowCooking = True

else:
op(‘geo4’).allowCooking = False

How can I use execute DAT in this case?