9_midi_controller.scd 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // MIDI note handling
  2. (
  3. var midiIn, synths, activeNotes;
  4. // Connect to MIDI
  5. MIDIClient.init;
  6. MIDIIn.connectAll;
  7. // Note On: add num to activeNotes and set synth gate to 1
  8. MIDIdef.noteOn(\noteOn, { |vel, num, chan, src|
  9. var freq = num.midicps;
  10. var index;
  11. //postln("Note On: " + num + " Velocity: " + vel);
  12. if (vel > 0) {
  13. // Find first available (nil) slot
  14. index = ~activeNotes.detectIndex({ |s| s.isNil });
  15. if (index.notNil) {
  16. ~synths[index].set(\gate, 1);
  17. ~synths[index].set(\freq, freq);
  18. ~synths[index].set(\amp, vel/127);
  19. ~activeNotes[index] = num; // Map note to synth index
  20. } {
  21. "No available synth slots!".postln;
  22. }
  23. } { // Treat as noteOff if it is a noteOn with velocity 0
  24. index = ~activeNotes.detectIndex({ |s| (s == num) });
  25. if (index.notNil) {
  26. ~activeNotes[index] = nil;
  27. ~synths[index].set(\gate, 0);
  28. }
  29. }
  30. });
  31. // Note Off: set synth gate to 0 and remove num from activeNotes
  32. MIDIdef.noteOff(\noteOff, { |vel, num, chan, src|
  33. var index;
  34. //postln("Note Off: " + num + " Velocity: " + vel);
  35. index = ~activeNotes.detectIndex({ |s| (s == num) });
  36. if (index.notNil) {
  37. ~activeNotes[index] = nil;
  38. ~synths[index].set(\gate, 0);
  39. }
  40. });
  41. // Run these functions directly
  42. "MIDI functions loaded.".postln;
  43. )