Here is a simple example with a Python client sending OSC messages to Sonic Pi. First, the Python client:
import random
import time
from pythonosc import udp_client
client = udp_client.SimpleUDPClient('127.0.0.1', 4559)
while True:
client.send_message("/bpm", random.randint(40, 200))
time.sleep(5)
The Python code establishes a client connection to the Sonic Pi OSC server which runs on port 4559
on my localhost (127.0.0.1
). OSC is a network protocol, so it doesn’t matter where the program runs from; only a UDP connection is needed, and the python-osc
library provides that. Next, I enter an infinite loop which will send OSC messages called bpm
every 5 seconds. The bpm
label was arbitrary - you can name your messages whatever you want, but that name / key is what you’ll use to gather data. The bpm
message is sending along a single randomly chosen number between 40 - 200 which I’ll use for the BPM.
The Python program can be run at this point and it will start sending UDP messages to port 4559. It doesn’t matter at this point if Sonic Pi is running, just that the messages won’t get received by anything.
Here is an example Sonic Pi code that will alter the BPM of a metronome as it receives messages:
# Initial BPM
set :bpm, 120
live_loop :receiver do
bpm_data = sync "/osc/bpm"
set :bpm, bpm_data[0]
end
live_loop :metronome do
with_bpm get(:bpm) do
sample :elec_ping if [1,0,1,0,1,0,1,0].ring.tick == 1
sleep 0.5
end
end
Make sure your Sonic Pi is set to be an OSC server in settings, run the above, and you should see / hear the metronome changing tempo every 5 seconds.
what do I need to launch them in the same time and make them speak between each other ?
It sounds like you probably want a ‘one-click’ solution where a user could launch the Python script and Sonic Pi with a single action? There are different ways you could do this - for example via a shell/bash script, or you could launch Sonic Pi from within your Python program. However, you’d likely need a buffer or few to execute after startup and I’m not sure the best way to accomplish that programmatically, but others will probably have some ideas. Not that you want to add another tool (from another language) into your setup, but there is a project that might suit you well for starting the Sonic Pi server and sending initial code to execute: GitHub - lpil/sonic-pi-tool: 🎻 Controlling Sonic Pi from the command line