9_midi_controller.scd 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. ~filterEnv.set(\gate, 1); // Triggers the filter envelope
  21. } {
  22. "No available synth slots!".postln;
  23. }
  24. } { // Treat as noteOff if it is a noteOn with velocity 0
  25. index = ~activeNotes.detectIndex({ |s| (s == num) });
  26. if (index.notNil) {
  27. ~activeNotes[index] = nil;
  28. ~synths[index].set(\gate, 0);
  29. ~filterEnv.set(\gate, 0); // Releases the filter envelope
  30. }
  31. }
  32. });
  33. // Note Off: set synth gate to 0 and remove num from activeNotes
  34. MIDIdef.noteOff(\noteOff, { |vel, num, chan, src|
  35. var index;
  36. //postln("Note Off: " + num + " Velocity: " + vel);
  37. index = ~activeNotes.detectIndex({ |s| (s == num) });
  38. if (index.notNil) {
  39. ~activeNotes[index] = nil;
  40. ~synths[index].set(\gate, 0);
  41. ~filterEnv.set(\gate, 0); // Releases the filter envelope
  42. }
  43. });
  44. // Run these functions directly
  45. "MIDI functions loaded.".postln;
  46. )