I’m starting an in_thread loop like so via OSC Command
stop if cotinueplay=0
How can I stop this loop (or the entire thread) with another OSC command?
I try sending a (continueplay=0) via OSC but no results.
Here is a demo program that starts and stops the loop using osc messages. In this case the messages are sent from this instance of Sonic Pi, but they could be sent from an external source, eg another computger running Sonic Pi on the same network. Note the use of the set and get commands to store the values of continueflag in the time_state where they can be accessed by the live_loops, and the syntax used to do this. See section 10.1 of the built in Tutorial for details. I’ve changed the time delay to 1 between the :E3 plays and stopped the live_loop after 10 seconds. Notice also that althouhg you send the osc message to /start you detect it with /osc/start YOu need to prepend /osc to every osc address you want sonic pi to detect.
#demo program by Robin Newman
use_osc "localhost",4559 #send OSC messages to localhost ie this program
set :continueplay,3 # set a dummy value (not 0 or 1 for continueplay, to start with)
live_loop :startcue do #wait for incoming /start OSC message
b = sync "/osc/start"
set :continueplay,1 # stat continueplay flag to 1
live_loop :stopcue do #wait for incvoming /stop OSC message
b = sync "/osc/stop"
set :continueplay,0 #set continueflag to 0
live_loop :play do # play loop
play :E3 if get(:continueplay)==1 # play :E3 if continueflag is 1
stop if get(:continueplay) ==0 #stop this loop (althouhg NOT the complete program if continue flag 0
osc "/start" #start message (This could be sent from an external source)
osc "/stop" #stop message (This could be sent from an external source)
Oh this response is cool. Thanks for this solution.
Is there a way to stop an “in_thread do…end” block?
If I spawn a thread how to stop it to reduce resources consumption?
stop is localised to the block in which it is running and will stop that, so just use it in a thread and it will stop just that thread. You can use a flag or condition set by a received OSC message to enable it when you want to do the stop.