Working with OSC as variables

Hi,

here is a lengthy example, which might help and provide some ideas how to cope with incoming messages from different controllers or switches. The live_loop :simulate_a_rotary_controller does what it says: Acctually Sonic Pi sends OSC messages to itself in this example:


use_osc "127.0.0.1", 9000

use_bpm 120

live_loop :simulate_a_rotary_controller do
  osc_send "127.0.0.1", 4559, "/rotary/controller/0", (line 0, 1, inclusive: true, steps: 20).reflect.tick
  sleep 0.25
end

# A very useful function provided by Robin Newman
define :parse_osc do | path |
  v = get_event(path).to_s.split(",")[6]
  if v != nil
    return v[3..-2].split("/")
  else
    return "Could not decipher osc path..."
  end
end

live_loop :osc_device_watcher do
  use_real_time
  m  = "/osc/**" # everything which comes in as osc ...
  data  = sync m
  seg   = parse_osc m
  puts "Seg contains these elements: #{seg}"
  puts "With 'seg' you can find out, which controller was used ..."
  puts "... and build contitional statements like the following ..."
  if seg[3] == "0" # if the controller 0 is being turned, change the volume from 'the_sample'
    puts "Simulated rotary controller sends:  #{data[0]}"
    # now store what's coming in into a variable
    set :vol_rotary_0, data[0]
    # and set the desired element via 'control' to this value during runtime
    control get(:the_sample), amp: get(:vol_rotary_0)
  end
end

live_loop :amen_controlled_by_osc do
  #stop
  s = sample :loop_amen, beat_stretch: 4, amp: get(:vol_rotary_0)
  set :the_sample, s
  sleep 4
end

Edit: Here is a short example by Robin.