Example #1
0
void createMidiFile(const char* filename, vector<vector<int> >& sequence) {
   MidiFile midifile;
   midifile.absoluteTicks();
   midifile.addTrack(1);
   int tpq = 120;
   double beat = 0.0;
   midifile.setTicksPerQuarterNote(tpq);


   MidiEvent tempo;
   tempo.setMetaTempo(60.0);
   tempo.track = 0;
   tempo.tick = 0;
   midifile.addEvent(tempo);

   int maxlen = 0;
   int i, j;
   for (i=0; i<(int)sequence.size(); i++) {
      if ((int)sequence[i].size() > maxlen) {
         maxlen = sequence[i].size();
      }
   }

   vector<int> notelist;
   MidiEvent noteon(0x90, 0, 64);
   MidiEvent noteoff(0x80, 0, 64);
   noteon.track  = 1;
   noteoff.track = 1;

   for (i=0; i<maxlen; i++) {
      notelist.clear();
      for (j=0; j<(int)sequence.size(); j++) {
         if (i<(int)sequence[j].size()) {
            notelist.push_back(sequence[j][i]);
         }
      }
      for (j=0; j<(int)notelist.size(); j++) {
         noteon[1]  = 0x7f & notelist[j];
         noteoff[1] = 0x7f & notelist[j];
         noteon.tick  = (int)(beat * tpq + 0.5);
         noteoff.tick = (int)(beat * tpq + 1 * tpq + 0.5);
         midifile.addEvent(noteon);
         midifile.addEvent(noteoff);
      }
      beat += 1.0;
   }

   midifile.sortTracks();
   midifile.write(filename);
}