InvisibleWrench / FlutterMidiCommand

A Flutter plugin to send and receive MIDI
BSD 3-Clause "New" or "Revised" License
95 stars 50 forks source link

How to convert received MidiPacket into NoteOn, NoteOff, etc messages? #55

Closed Gilianp closed 2 years ago

Gilianp commented 2 years ago

Hi, thanks again for the plugin :)

How to convert received MidiPacket into NoteOn, NoteOff, etc messages? When I subscribed in onMidiDataReceived, only MidiPacket are received, but I can't figure out how convert then in "parsed (NoteOn, NoteOff, etc)" midi messages properly for use in my app. Thanks

mortenboye commented 2 years ago

MidiPackets/Messages are usually between 1 and 3 bytes long, with each bytes containing different data depending on the type of midi message.

Full spec. can be found here (requires (free) login).

But for NoteOn and Off, the three bytes in a message will look like this: TTTTCCCC 0KKKKKKK 0VVVVVVV

where the 4 T-bits define the type of Midi message the 4 C-bits define the Midi channel the 7 K-bits define the key of the note the 7 V-bits define the velocity of the note

and you can handle that using this as a starting point:

var data = packet.data;
if (data.length == 3) {
  var status = data[0];
  var type = status & 0xF0;
  var channel = status & 0x0F;
  var note = data[1];
  var vel = data[2];

  if (type == 0x90) {
    // Note On
  } else if (type == 0x80) {
    // Note Off
  }
}

Remember that a NoteOn message (0x90) with a Velocity of 0, signifies the same as a NoteOff message for the same key.