Hey Michael!

I use a factory-esque pattern + a "Voice" interface, like this:

class MyVoice
{
    SqrOsc s  => LPF f => ADSR adsr => dac;
    
    fun void setFreq(float freq) { freq => s.freq; }
    fun void noteOn() { 1 => adsr.keyOn; }
    fun void noteOff() { 1 => adsr.keyOff; }
}

class Poly
{
    MyVoice voices[10];
    MyVoice @ voiceForNote[127];
    0 => int voiceIndex;
    
    fun MyVoice allocateVoiceForNote(int note)
    {
        voices[voiceIndex] @=> MyVoice v;
        v @=> voiceForNote[note];
        (voiceIndex+1)%voices.size() => voiceIndex;
        return v;
    }
    
    fun MyVoice getVoiceForNote(int note)
    {
        return voiceForNote[note];
    }
    
    fun void returnVoiceForNote(int note)
    {
        null @=> voiceForNote[note];
    }
}

Fill in MyVoice as needed with the provided methods, as a bare minimum (you may wish to have other methods like for controlling envelope or filter, etc.). allocateVoiceForNote() pulls out the next voice whenever you need it (e.g. in response to MIDI keyDown). getVoiceForNote() is used to get the voice associated with a note e.g. in response to MIDI keyOff, and returnVoiceForNote() indicates that the voice allocated for a given note is no longer needed (also in response to MIDI noteOff). 

allocateVoiceForNote() uses a round-robin-style voice stealing approach, but more sophisticated techniques are possible/often desirable, e.g. least recently used. 

This is hastily typed pseudocode, but I have actual examples I can dig up if desired. 

Spencer



On Mon, Dec 11, 2017 at 2:02 PM, Michael Heuer <heuermh@gmail.com> wrote:
All,

I mostly play guitar and single-finger bass lines, but now my sons are starting to play keys for reals and so I'm curious what the typical patterns for implementing polyphony with MIDI might be?

Thanks in advance,

   michael


_______________________________________________
chuck-users mailing list
chuck-users@lists.cs.princeton.edu
https://lists.cs.princeton.edu/mailman/listinfo/chuck-users




--
Spencer Salazar, PhD
Special Faculty
Music Technology: Interaction, Intelligence, and Design
California Institute of the Arts

ssalazar@calarts.edu | +1 831.277.4654