 
   // Get an available OPL2 channel and setup instrument parameters.
   byte i = getFreeChannel(channel);
-  channelMap[i].midiChannel = channel;
-  channelMap[i].midiNote    = note;
   opl2.setInstrument(i, instruments[programMap[channel]]);
+  channelMap[i].midiChannel  = channel;
+  channelMap[i].midiNote     = note;
+  channelMap[i].midiVelocity = round(velocity / 127.0);
+  channelMap[i].op1Level     = round((63 - opl2.getVolume(i, OPERATOR1)) / 63.0);
+  channelMap[i].op2Level     = round((63 - opl2.getVolume(i, OPERATOR2)) / 63.0);
 
   // Set operator output levels based on note velocity.
-  float volume = velocity / 127.0;
-  byte opl2VolumeOP1 = 63 - opl2.getVolume(i, OPERATOR1);
-  byte opl2VolumeOP2 = 63 - opl2.getVolume(i, OPERATOR2);
-  opl2.setVolume(i, OPERATOR1, 63 - (opl2VolumeOP1 * volume));  
-  opl2.setVolume(i, OPERATOR2, 63 - (opl2VolumeOP2 * volume));
+  setOpl2ChannelVolume(i, channel);
 
   // Calculate octave and note number and play note!
   note = max(24, min(note, 119));

struct ChannelMapping {
  byte midiChannel;
  byte midiNote;
};



ChannelMapping channelMap[OPL2_CHANNELS];
byte lastUsed[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
byte programMap[MIDI_CHANNELS];
float channelVolumes[MIDI_CHANNELS];


void setup() {
  // Serial.begin(115200);

  usbMIDI.setHandleNoteOn(onNoteOn);
  usbMIDI.setHandleNoteOff(onNoteOff);
  usbMIDI.setHandleProgramChange(onProgramChange);
  usbMIDI.setHandlePitchChange(onPitchChange);
  usbMIDI.setHandleControlChange(onControlChange);
  usbMIDI.setHandleSystemReset(onSystemReset);
  onSystemReset();
}


