-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtouchosc.py
More file actions
executable file
·592 lines (429 loc) · 16.3 KB
/
touchosc.py
File metadata and controls
executable file
·592 lines (429 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#!/usr/bin/python
# Pipe OSC messages from TouchOSC mobile app to MIDI output and/or forward to Sonic Pi via OSC
# You will need to install the python-rtmidi and pyosc libraries; try one of these commands:
#
# $ pip install --pre python-rtmidi
# $ easy_install python-rtmidi
import socket, OSC, re, threading, math
import time, sys
from numpy import interp
import rtmidi
from rtmidi.midiutil import open_midiport
from rtmidi.midiconstants import *
SEND_SONIC = False # set to true to send
# get machine's IP address, so we don't have to set it manually
import subprocess
ipaddr = subprocess.Popen(["ipconfig", "getifaddr", "en0"], stdout=subprocess.PIPE).communicate()[0].rstrip()
print ipaddr
receive_address = ipaddr, 9000
ableton_receive_address = ipaddr, 1234
# Sonic PI only accepts OSC connections from the same machine, i.e. localhost
send_address_pi = 'localhost', 4557
# send_address_phone = '10.22.0.150', 9999 # your phone's IP address, for sending back current scale name, etc
# send_address_phone = '192.168.1.102', 9999 # your phone's IP address, for sending back current scale name, etc
send_address_phone = '192.168.1.107', 9999 # your IPAD's IP address, for sending back current scale name, etc
phone = OSC.OSCClient()
try:
phone.connect(send_address_phone)
except:
print("phone: no connection")
def sendosc(client, path, args):
msg = OSC.OSCMessage(path)
msg.append(args)
print msg
client.send(msg)
mnote = 60
mchan = 0
chan_max = 6
last_note_time = 0
last_z_trig = 0
last_note = 0
last_z = 0
last_x = 0
z_reset = True
x_reset = True
hold_state = 0
mindex = 0
midiout = rtmidi.MidiOut()
available_ports = midiout.get_ports()
if available_ports:
midiout.open_port(0)
else:
midiout.open_virtual_port("My virtual output")
synth_val = 0
attack_val = 0.1
release_val = 0.1
# START SCALE DEFINITIONS
current_scale = 0
MIDI_NOTE_MIN = 19
MIDI_NOTE_MAX = 109
MIDI_RANGE = MIDI_NOTE_MAX - MIDI_NOTE_MIN
MIN_VEL = 20
MAX_VEL = 80
instrument_names = ['Drums', 'Piano']
synth_names = [':beep', ':blade', ':chipbass', ':dark_ambience', ':dpulse', ':dsaw', ':dtri', ':dull_bell', ':fm', ':growl', ':hollow', ':hoover', ':mod_beep', ':mod_fm', ':mod_sine', ':mod_tri', ':piano', ':pluck', ':pretty_bell', ':prophet', ':pulse', ':saw', ':sine', ':square', ':subpulse', ':supersaw', ':tb303', ':tri', ':zawa']
use_synth = ':fm'
Test1 = [0, 2, 5, 6, 7]
Test2 = [0, 2, 4, 7, 8]
Test3 = [0, 3, 5, 8, 9]
Test4 = [0, 2, 6, 11]
Test5 = [0, 4, 7, 9]
Arabian = [0, 2, 4, 5, 6, 8, 10]
Balinese = [0, 1, 3, 7, 8]
Gypsy = [0, 1, 4, 5, 7, 8, 11]
MajorChord = [0, 4, 7]
MinorChord = [0, 3, 7]
Min7 = [0, 3, 7, 10]
Sus4 = [0, 5, 7]
Pelog = [0, 1, 3, 7, 10]
Major = [0, 2, 4, 5, 7, 9, 11]
Minor = [0, 2, 3, 5, 7, 8, 10]
scales = [Test1, Test2, Test3, Test4, Test5, Arabian, Balinese, Gypsy, MajorChord, MinorChord, Min7, Sus4, Pelog, Major, Minor]
scale_names = ['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Arabian', 'Balinese', 'Gypsy', 'MajorChord', 'MinorChord', 'Min7', 'Sus4', 'Pelog', 'Major', 'Minor']
#print(scales)
for s in range(0, len(scale_names)):
print("[" + str(s) + "] " + scale_names[s])
print("\n------------- \n")
num_scales = len(scales)
sind = 0
scales_table = [[]] * num_scales
#print(scales_table[2])
#print(scales_table)
#print("len: " + str(num_scales))
key = 0
scale = 14
scale_group = [1,2,3,4,5]
# generate a true/false table of whether each note is 'on' in this position in scale
for sc in scales:
#print("ind: " + str(sind))
scales_table[sind] = [False]*12
#print(scales_table[sind])
for pos in sc:
#print("pos: " + str(pos))
scales_table[sind][pos] = True
sind += 1
#print(scales_table)
# ugly ass 3D array init... so ugly and bad, but apparently necessary
scale_notes = [[]] * 12
for i in range(0, 12):
scale_notes[i] = [[]] * num_scales
for j in range(0, num_scales):
scale_notes[i][j] = [[]] * 12
for key in range(0, 12):
for s in range(0, num_scales):
for k in range(0,12):
relative_note = (key + k) % 12
if scales_table[s][k] == True:
scale_notes[key][s][relative_note] = True
else:
scale_notes[key][s][relative_note] = False
#print(scale_notes)
# ugly ass 3D array init
scale_midi_notes = [[]] * 12
#scale_midi_notecount = [[]] * 12
for i in range(0, 12):
scale_midi_notes[i] = [[]] * num_scales
#scale_midi_notecount[i] = [0] * num_scales
for j in range(0, num_scales):
scale_midi_notes[i][j] = [False] * MIDI_RANGE
# generate the list of valid midi notes for each scale in each key
for i in range(0, 12):
for j in range(0, num_scales):
note_count = 0
for k in range(MIDI_NOTE_MIN, MIDI_NOTE_MAX):
if scale_notes[i][j][(k % 12)] == True:
scale_midi_notes[i][j][note_count] = k
note_count += 1
scale_midi_notes[i][j] = scale_midi_notes[i][j][:note_count] #truncate to only set values
# END SCALES
if len(sys.argv) > 2:
current_scale = int(sys.argv[2])
print "\n\nscale: " + scale_names[current_scale] + "\n\n"
else:
current_scale = 6
#balinese
if len(sys.argv) > 1:
# minst = int(sys.argv[1])
# # print minst
SEND_SONIC = True
pi = OSC.OSCClient()
try:
pi.connect(send_address_pi)
except:
print("no connect")
# define a message-handler function for the server to call.
def test_handler(addr, tags, stuff, source):
print("test_handler ---")
print("received new osc msg from %s" % OSC.getUrlStr(source) )
print("with addr : %s" % addr)
print("typetags %s" % tags)
print("data %s" % stuff)
# msg = OSC.OSCMessage()
# msg.setAddress(addr)
# msg.append(stuff)
# c.send(msg)
# print("return message %s" % msg)
# print("---")
def hold_handler(addr, tags, stuff, source):
global hold_state
if stuff[0] == 1.0:
hold_state = 1
else:
hold_state = 0
#mchan = int(stuff[0] * chan_max)
#print mc
def chan_handler(addr, tags, stuff, source):
global mchan, use_synth, SEND_SONIC
#print addr, stuff
mchan = int(stuff[0] * chan_max)
use_synth = int(stuff[0] * len(synth_names))
print mchan
if SEND_SONIC:
print synth_names[use_synth]
def scale_handler(addr, tags, stuff, source):
global current_scale
# set scale
if stuff[0] < 1.0:
# current_scale = int ( interp(stuff[0], [0, 1], [0, len(scales) - 1 ]) ) #math.ceil( (len(scales) - 1 ) * stuff[0] )
current_scale = int( (len(scales)) * stuff[0] )
print len(scales), stuff[0], current_scale
print "NEW scale: " + scale_names[current_scale] + " (" + str(current_scale) + ")"
print
sendosc(phone, "/1/labelscale", [ scale_names[current_scale] ])
def accxyz_handler(addr, tags, stuff, source):
#print("typetags %s" % tags)
#print("data %s \r" % stuff, end="")
#print stuff[0]
send_pi( stuff[0], stuff[1], stuff[2] )
def push_handler(addr, tags, stuff, source):
if stuff[0] == 1.0:
# send_osc( "play 90" )
midiout.send_message([0x90 + mchan, 38, 100])
def pedal_handler(addr, tags, stuff, source):
#if stuff[0] == 1.0:
print("\npedal\n")
midiout.send_message([0xb0 + mchan, 123, 0])
def send_osc(args):
try:
print args
msg = OSC.OSCMessage("/run-code")
#cmd = "play " + str(note) + ", attack: 0.001"
msg.append([0, args])
pi.send(msg)
#pi.send( OSC.OSCMessage("/run", [22]) ) # why the fuck does this no longer work?
# print "sent " + args
except Exception as ex:
print ex
def send_pi(accx, accy, accz):
global last_note_time, last_note, last_z_trig, last_x, last_z, x_reset, z_reset, mnote, mindex
fixedx = interp(accx,[-9.0, 9.0],[-0.5,0.5])
note = int( 80 + (fixedx * 44) )
vz = accz - last_z
vx = accx - last_x
#print "vz: " + str(vz) + " (z: " + str(accz) + ")"
# print "z: " + str(accz)
# Z-axis triggering using calculated Z-accel values...doesn't really work, or anyway not as well as just using the vz value
# if 0 and vz < -20.0 and accz < -12.0:
# # silence
# print("\npedal\n")
# midiout.send_message([0xb0 + mchan, 123, 0])
# yrot = interp(accy, [-9, 9], [0,1])
# mnote = int( (yrot * 40) + 50 )
try:
sc = current_scale
if hold_state:
# hold current note ( but allow 1 note on either side of current note)
span = 2
xrot_hold = int(interp(accx, [-8, 8], [1, -1])) * span # consider also [-3, 3] * 2 or * 3 - more chord like?
if mchan == 0:
# drums, hold single note, i.e. drum
mnote = mnote
else:
mind_hold = mindex + xrot_hold
mnote = scale_midi_notes[key][current_scale][mind_hold]
else:
# calculate note based on x rotation, only if hold button not pressed
xrot = interp(accx, [-10, 10], [1,0])
#print xrot
if mchan == 0:
mnote = (xrot * 14) + 38
else:
mindex = int( (len(scale_midi_notes[key][current_scale])-1) * xrot) # yrot)
mnote = scale_midi_notes[key][current_scale][mindex]
#print "yrot mnote= " + str(mnote)
except IndexError:
print "nope: " + str(mindex) + ", max " + str(len(scale_midi_notes[key][sc]))
# end calc
# trigger on vz, ensure one direction only with accz positive check
if vz > 4.0 and accz > 0 and z_reset : #time.time() - last_z_trig > 0.01:
z_reset = False
zmag = interp(vz,[4.0, 30.0],[10, 110])
print "TRIG vz: " + str(vz) + " (z: " + str(accz) + ") note: " + str(mnote) + " zvel: " + str(int(zmag)) + " (accy: " + str(accy) + ")"
#print "play mnote= " + str( mnote )
# fudge to ignore the regular triggering of the highest note from weird accel values
if mnote != 108 :
if SEND_SONIC: #and last_note != note and time.time() - last_note_time > 0.1:
amp = interp(vz, [4.0, 45.0], [0.1, 1.2])
ampstr = ", amp: " + str(amp)
sus = interp(accy, [2, 9], [0, 0.5])
sustainstr = ", attack: " + str(sus)
send_osc( "set_sched_ahead_time! 0.0001; use_synth " + synth_names[use_synth] + "; play " + str(int(mnote+30)) + ampstr + sustainstr )
# last_note_time = time.time()
else:
midiout.send_message([0x90 + mchan, mnote, int(zmag)]) #minst, int(zmag)])
last_z_trig = time.time()
# print "z trig!"
# trigger on x-axis shake too... doesn't work too well right now
# if 0:
# if abs(vx) > 5.0 and x_reset : #time.time() - last_z_trig > 0.01:
# x_reset = False
# # send_osc( "play 60" )
# xmag = interp(abs(vx),[5, 30],[30, 120])
# print "\nTRIG vx: " + str(vx) + " (z: " + str(accx) + ") xvel: " + str(int(xmag)) + " (accy: " + str(accy) + ") note " + str(mnote)
#
# #print "play mnote= " + str( mnote )
# midiout.send_message([0x90 + mchan, mnote, int(xmag)]) #minst, int(zmag)])
#
# if not x_reset and accx < 2.0 and accx > 0.0:
# x_reset = True
#
if not z_reset and accz <= 6.0:
z_reset = True
last_note = note
last_z = accz
last_y = accy
# end send-pi function
# define a message-handler function for the server to call.
def fader_handler(addr, tags, stuff, source):
id = addr.split("/").pop()
note = interp(stuff[0], [0.0, 1.0], [30, 120])
print("id : %s" % id)
print("note_count : %s" % note)
print("with addr : %s" % addr)
print("typetags %s" % tags)
print("data %s" % stuff[0])
# msg = OSC.OSCMessage()
# msg.setAddress(addr)
# msg.append(stuff)
# print("return message %s" % msg)
# print("---")
# send_osc("play " + str(note) + ";")
send_osc("touchosc_recv('" + addr + "', " + str(stuff[0]) + ")")
# define a message-handler function for the server to call.
def keys_handler(addr, tags, stuff, source):
note = addr.split("/").pop()
if note == "z":
print("Z!!")
return
note = int(note) + 47
val = float(stuff[0])
print("note: %s" % note)
print("with addr : %s" % addr)
print("typetags %s" % tags)
print("data %s" % stuff[0])
# msg = OSC.OSCMessage()
# msg.setAddress(addr)
# msg.append(stuff)
# print("return message %s" % msg)
# print("---")
# synth = "use_synth synth_names[ (" + str(synth_val) + " * synth_names.length).to_i ]; "
if val > 0:
asdr = ", attack: " + str(attack_val) + ", release: " + str(release_val)
synth = "use_synth synth_names[ (" + str(synth_val) + " * synth_names.length).to_i ]; "
send_osc(synth + "play " + str(note) + ", sustain: " + str(val) + asdr)
else:
print "NOTEOFF"
def xy_handler(addr, tags, stuff, source):
global attack_val, release_val
if addr == '/2/xy/1':
attack_val = float(stuff[1]) #x
release_val = 1.0 - float(stuff[0]) #x
print attack_val, release_val
return
# call sonic pi function with signature: touchosc_recv('/page/xy/id/', [xval, yval])
send_osc("touchosc_recv('" + addr + "', [" + str(stuff[1]) + ", " + str(stuff[0]) + "])")
def toggle_handler(addr, tags, stuff, source):
send_osc("touchosc_recv('" + addr + "', " + str(stuff[0]) + ")")
#
#
# def toggle_handler(addr, tags, stuff, source):
# send_osc("touchosc_recv('" + addr + "', " + str(stuff[0]) + ")")
def able_default_handler(addr, tags, stuff, source):
# print "DEFAULT"
# print stuff
return
# such bullshit
able_vel = 0
def able_vel_handler(addr, tags, stuff, source):
global able_vel
print stuff
# send_osc("touchosc_recv('" + addr + "', " + str(stuff[0]) + ")")
able_vel = stuff[0]
def able_handler(addr, tags, stuff, source):
print stuff
# send_osc("touchosc_recv('" + addr + "', " + str(stuff[0]) + ")")
if stuff[0] == 60 and able_vel > 0:
send_osc("cue :live")
able = OSC.OSCServer(ableton_receive_address)
able.addDefaultHandlers()
able.addMsgHandler("default", able_default_handler)
able.addMsgHandler("/Note1", able_handler)
able.addMsgHandler("/Velocity1", able_vel_handler)
s = OSC.OSCServer(receive_address)
s.addDefaultHandlers()
s.addMsgHandler("/accxyz", accxyz_handler)
s.addMsgHandler("/1/push7", push_handler)
s.addMsgHandler("/1/fader1", scale_handler)
s.addMsgHandler("/1/fader2", chan_handler)
s.addMsgHandler("/1/push1", pedal_handler) #top left
s.addMsgHandler("/1/push4", hold_handler) #top middle
# sonic pi
s.addMsgHandler("/1/xy/1", xy_handler)
s.addMsgHandler("/1/xy/2", xy_handler)
s.addMsgHandler("/1/xy/3", xy_handler)
s.addMsgHandler("/1/xy/4", xy_handler)
s.addMsgHandler("/2/xy/1", xy_handler)
s.addMsgHandler("/2/toggle/1", toggle_handler)
s.addMsgHandler("/4/push/1", toggle_handler)
s.addMsgHandler("/3/push/1", toggle_handler)
for y in range(1, 9):
for x in range(1, 17):
s.addMsgHandler("/3/multitoggle/1/" + `y` + "/" + `x`, toggle_handler) #top middle
s.addMsgHandler("/4/multitoggle/1/" + `y` + "/" + `x`, toggle_handler) #top middle
for y in range(1, 20):
s.addMsgHandler("/1/fader/"+`y`, fader_handler)
s.addMsgHandler("/2/fader/"+`y`, fader_handler)
s.addMsgHandler("/3/fader/"+`y`, fader_handler)
s.addMsgHandler("/4/fader/"+`y`, fader_handler)
s.addMsgHandler("/4/rotary/"+`y`, fader_handler)
for i in range(1, 25 ):
s.addMsgHandler("/2/key/" + `i`, keys_handler)
s.addMsgHandler("/3/multifader/1/"+`i`, fader_handler)
s.addMsgHandler("/4/multifader/1/"+`i`, fader_handler)
def f3_handler(addr, tags, stuff, source):
global synth_val
synth_val = stuff[0]
s.addMsgHandler("/2/fader/3", f3_handler )
for addr in s.getOSCAddressSpace():
print( addr )
# Start OSCServer
print("\nStarting OSCServer. Use ctrl-C to quit.")
st = threading.Thread( target = s.serve_forever )
st.start()
# and that's it for the OSC
if ableton_receive_address:
print("\nStarting Ableton Live sync server.")
ab = threading.Thread( target = able.serve_forever )
ab.start()
try :
while 1 :
time.sleep(1)
except KeyboardInterrupt :
print ("\nClosing OSCServer.")
s.close()
print ("Waiting for Server-thread to finish")
st.join() ##!!!
if ableton_receive_address:
able.close()
ab.join()
print ("Done")