OSC Listening

Example directory (scamp): examples/Tutorial/28_osc_listening

Download: 28_osc_listening.zip

Run osc_listener.py first, which uses Session.register_osc_listener to listen for OSC messages and play back notes and horrific bagpipe clusters. Then run osc_sender.py which simulates an external program sending OSC messages to to the listener script, leading to the aforementioned notes and horrific bagpipe clusters.

osc_listener.py: Listener script, which uses register_osc_listener() to register callback functions that play notes and bagpipe clusters.
from scamp import *

s = Session()

piano = s.new_part("piano")
flute = s.new_part("flute")
bagpipe = s.new_part("bagpipe")


# ------------------ CALLBACK FUNCTIONS -----------------
# Note that all notes are played with blocking=False.
# Callback functions run with the scheduler frozen, so must not pass time.

def play_note_callback(osc_address, pitch, volume, length):
    if osc_address.split("/")[-1] == "piano":
        piano.play_note(pitch, volume, length, blocking=False)
    elif osc_address.split("/")[-1] == "flute":
        flute.play_note(pitch, volume, length, blocking=False)


def bagpipe_callback(osc_address):
    bagpipe.play_chord([70, 71, 72, 73, 74, 75, 76], 0.5, 0.2, blocking=False)


s.register_osc_listener(5995, "/play_note/*", play_note_callback)
s.register_osc_listener(5995, "/play_bagpipe_cluster", bagpipe_callback)


s.wait_forever()
osc_sender.py: Sender script, mimicking an external application sending OSC messages.
from pythonosc import udp_client
import time


client = udp_client.SimpleUDPClient("127.0.0.1", 5995)

# play a chromatic scale on the piano
for x in range(65, 85):
    client.send_message("/play_note/piano", [x, 0.5, 0.1])
    time.sleep(0.1)

# play a horrifying bagpipe cluster
client.send_message("/play_bagpipe_cluster", [])
time.sleep(0.5)

# play a chromatic scale on the flute
for x in range(65, 85):
    client.send_message("/play_note/flute", [x, 0.5, 0.1])
    time.sleep(0.1)

# play another horrifying bagpipe cluster
client.send_message("/play_bagpipe_cluster", [])
time.sleep(0.5)

# play a chromatic scale alternating between flute and piano
for x in range(65, 85):
    client.send_message("/play_note/" + ("flute", "piano")[x % 2], [x, 0.5, 0.1])
    time.sleep(0.1)