Pass a text string to Sonic Pi from outside script or code?



Inspired by the thread, [Play A Fairy Song by William Shakespeare](http://Play A Fairy Song by William Shakespeare), I’m working on an art piece that would allow people to type in some text, and then Sonic Pi would play a randomly generated composition based on the text they typed.

I have the Sonic Pi code working the way I like with the text in a variable. Now I’m faced with the task of taking user input with another piece of code and passing the text string to Sonic Pi. Has this been done before? Is there anything built into Sonic Pi that would allow this?

Thanks for any pointers or guidance.



Hi Tom
You could send a text string with an OSC command which Sonic Pi could pick up.
Here is an example using a python script to receive and send a text using OSC which is picked up by Sonic Pi. I named the script

#!/usr/bin/env python3
#send command to SP from input
#need to install pythonosc library
#use pip3 install pythonosc
#I saved the script as
from time import sleep
from pythonosc import udp_client
import argparse
import sys

def control(spip):
    sender = udp_client.SimpleUDPClient(spip,4559)
    while True:
            instr = input('Enter input line: ')
            if len(instr)> 0:
              sender.send_message('/control',instr) #sends entered command
              print("null input")
        except KeyboardInterrupt:

if __name__=="__main__":
    parser = argparse.ArgumentParser()
    default="", help="The ip Sonic Pi listens on")
    args = parser.parse_args()
    print("Sonic Pi on ip",spip)

Note you need to install the pythonosc library
I used pip3 install pythonosc

on the receiving end in Sonic Pi

live_loop :test do
  n=sync "/osc*/control"
  case n[0]
  when "low"
    play 60
  when "med"
    play 72
  when "high"
    play 84
  when "chord"
    play chord(:c,:major)
    puts "command not recognised"

This will respond to the commands:

typed into the python script.
if you set the python script to be executable from the command line.
chmod +x

To start the script you can then use
./ (assuming the script is running on the same computer as Sonic Pi)

at the prompt, type in one of the recognised commands
low, med, high or chord and press enter

If you are using Sonic Pi on a difffernt computer you can start the scriipt using
./ --sp

In this case you must ensure that Sonic PI has the flag to accept external OSC commands ticked on the Prefs IO tab.

The python script traps and ignores a mull input (just pushing return). Also the Sonic Pi script flags up commands it doesn’t understand.

Hoe the above is useful to you.

1 Like

That looks it will solve my problem. Thanks!


1 Like