Midifile View on GitHub

Off switch


Switch note-offs between 0x90 w/ 0 velocity and 0x80 styles. The MIDI protocol allows two types of note-off messages: (1) using the a command byte starting with the hex digit "8" that always indicates a note-off message for a given key with a given off-velocity, and (2) using note-on commands (starting with the hex digit "8"), but setting the attack velocity to 0. The following program can convert between these two different styles. The default behavior is to convert all note-off messages to the "8" style. If the -0 option is used, the note-offs will be converted into the "9" style note-off message which use a zero attack velocity within a note-on message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "MidiFile.h"
#include "Options.h"
#include <iostream>
using namespace std;

int main(int argc, char** argv) {

   Options options;
   options.define("0|O|o|z|9|zero=b", 
      "Set note-offs to note-on messages with zero velocity.");
   options.process(argc, argv);
   bool zeroQ = options.getBoolean("zero");
   if (options.getArgCount() != 2) {
      cerr << "Usage: " << options.getCommand() << " input.mid output.mid\n";
      exit(1);
   }

   MidiFile midifile;
   midifile.read(options.getArg(1));
   if (!midifile.status()) {
      cerr << "Error: could not read file" << options.getArg(1) << endl;
      exit(1);
   }
   for (int track=0; track<midifile.size(); track++) {
      for (int event=0; event<midifile[track].size(); event++) {
         if (!midifile[track][event].isNoteOff()) {
            continue;
         }
         if (zeroQ) {
            midifile[track][event].setCommandNibble(0x90);
            midifile[track][event][2] = 0;
         } else {
            midifile[track][event].setCommandNibble(0x80);
         }
      }
   }
   midifile.write(options.getArg(2));

   return 0;
}
Library functions used in this example:
  • MidiFile::getEventCount
  • MidiFile::getTrackCount
  • MidiFile::read
  • MidiFile::status
  • MidiFile::write
  • MidiMessage::isNoteOff
  • MidiMessage::setCommandNibble
  • Options::define
  • Options::getArg
  • Options::getArgCount
  • Options::getBoolean
  • Options::getCommand
  • Options::process