Repeat same function, thread already exists

So I tried to build a new song and have trouble adding more programming logic behind it instead of just placing all commands just one after eachother making the song a mess to read.

I have a defined function that accepts a number, the number is used for a loop. When I try to start that function again, it doesnt trigger because the threads inside the function already exist.
I’ve placed a very simplified version of what I want to achieve here.

define :repeat do |n|
  in_thread(name: :bass) do
    n.times do
      play 65
      sleep 1
    end
  end
  in_thread(name: :synth) do
    n.times do
      play 90
      sleep 1
    end
  end
end

repeat 2
sleep 2
repeat 1

I know you can stop a thread with ‘stop’ but if I put this stop at the end of the thread, it doesn’t reach the stop in time before the second execution. Is there a way to solve this?

If you set the sleep to 3 between each call of the function it works (but the timing is off then). Musicaly the timing is right, but the sound (echo) isn’t over yet after 2 seconds so the thread is still active.

Do you need the threads at all? If you change it to:

define :repeat do |n|
  n.times do
    play 65
    sleep 1
  end
  n.times do
    play 90
    sleep 1
  end
end

repeat 2
repeat 1

Then you can remove the sleep in between the calls and it will just play them one after the other.

If you do need the threads in the more complicated version, you could just not give them a name, and then you’ll be able to start a second copy while the previous one is still finishing.

I think so, both synths need to play at the same time. In your example you would have n times 65 followed by n times 90. I need n times 65+90 at the same time.

Genius yet so logical, hope this works, I’ll check this evening at home.

Thanks! This did the trick. I’ll just add #comments to ‘name’ my threads.

1 Like

I need n times 65+90 at the same time.

define :repeat do |n| 
n.times do 
play 65 
play 90
sleep 1 
end 

repeat 2 
repeat 1