Sonic Pi controlled from scratch

Sonic Pi is great software to produce sounds and to program melodies.

Sonic Pi has an API which allows to use some of the program statements from an external program. There are some places in the web where this feature is used with erlang- or ruby-code.

This adapter for scratchClient and the programming in scratch  is not intended to be a replacement to the Sonic Pi programming language. The reason is the timing of commands in scratch, which is not very precise and command execution delays are audible. But it can be used as a high quality sound generator for scratch games.

The API uses Open Sound Control OSC-format for the messages, so the Sonic Pi commands needs to be packed into this format. This format packs strings into a byte stream with null-bytes as terminators. An example is sending ‘play 60’, which needs the basic parameters ‘/run-code agent-name code’; the agent used is SONIC_PI_CLI and the command part is here ‘play 60’.

The OSC message is as follows

b'/run-code\x00\x00\x00,ss\x00SONIC_PI_CLI\x00\x00\x00\x00play 60\x00'

The strings are zero padded to 4 byte boundaries; the type of option is given by the two string-types ‘s’ after the command.

This conversion is done with the python_osc library; this library needs to be installed in addition to the standard install procedure.

sudo pip3 install python_osc

This library is available for python3 only. As scratchClient is continuously moving towards python3, this is not a restriction.

The software runs on linux and windows. scratchClient and Sonic Pi need to run on same machine, as Sonic Pi accepts only local connections.

Commands are ‘play 50’ for a simple beep, or ‘use_synth :chiplead ; play 80,release: 0.08 ; sleep 0.1 ; play 83, release: 0.08’ for a sequence of notes.

sonic.gif

In scratch, just set a variable sonicpi_cmd to the command needed.
More details in the scratchClient docs in http://www.heppg.de/ikg/administration/ … lient.html

The setup requires to have Sonic Pi running on same computer as scratchClient.
The commands executed are displayed in Sonic Pi window in the protocol-pane.

Errors in commands are displayed in the Sonic Pi window, so when no sound is produced it is a good place to look.

A more advances example is ‘Alle meine Entchen’ played from a list of sounds and a second list with time delays.

The script uses two lists to produce sound. ‘ame’ is containing sonic pi commands, ‘amd’ is providing timing information.

With these two lists, the script is just iterating through the list and sending commands to sonicpi_cmd-variable. As scratch is not sending out variable information when content does not change, it is needed to reset the information to an empty string in order to get notes repeated.

The scratch 1.4 project can be downloaded here.

Have fun !