Miskatonic University Press

Passing blocks to a thread in Sonic Pi

sonic.pi music code

A short example of how to pass a block to a thread in Sonic Pi, where it will be run and control will return to you immediately. The block can contain whatever you want. (Thanks to Sam Aaron, creator of Sonic Pi, for this; he sent it to the mailing list but I can’t find the original now.)

define :play_in_a_thread do |&block|
  in_thread do

play_in_a_thread do
   play :c4
   sleep 180
   play :e4
   sleep 180
   play :g4

play :c3

The play_in_a_thread (you can call it whatever you want) function will take whatever block you give it, and combined with Sonic Pi’s in_thread this parcels the block off, runs it, and returns control. In this example the C major chord will take 6 minutes to play, but the two Cs (:C4 and :C3) will play at the same time. You can call play_in_a_thread as many times as you want, from anywhere. You can pass in whatever you want, simple or complex, it doesn’t matter, Sonic Pi will handle it and let the program flow continue uninterrupted.

This is part of Ruby (in and on which Sonic Pi is built), and tells the function to expect a block to be passed in. The block operator (it’s also called an ampersand operator) section of the Ruby documentation on methods explains more.

Thanks to Sonic Pi, I’ve learned something new about Ruby.