I’m trying to generate midi file and play it on Android. I found android-midi-lib, but there are almost no any documentation about this library. I tried to run example from this lib. It works. But there is delay about 6 seconds before track from my notes start playing. I don’t know anything about notes and midi format. Everything is new for me.
Here is my code:
public class MyActivity extends Activity {
private MediaPlayer player = new MediaPlayer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MidiTrack tempoTrack = new MidiTrack();
MidiTrack noteTrack = new MidiTrack();
// 2. Add events to the tracks
// 2a. Track 0 is typically the tempo map
Tempo t = new Tempo();
t.setBpm(228);
tempoTrack.insertEvent(t);
// 2b. Track 1 will have some notes in it
for(int i = 0; i < 128; i++) {
int channel = 0, pitch = i, velocity = 100;
NoteOn on = new NoteOn(i*480, channel, pitch, velocity);
NoteOff off = new NoteOff(i*480 + 120, channel, pitch, 0);
noteTrack.insertEvent(on);
noteTrack.insertEvent(off);
}
// It's best not to manually insert EndOfTrack events; MidiTrack will
// call closeTrack() on itself before writing itself to a file
// 3. Create a MidiFile with the tracks we created
ArrayList<MidiTrack> tracks = new ArrayList<MidiTrack>();
tracks.add(tempoTrack);
tracks.add(noteTrack);
MidiFile midi = new MidiFile(MidiFile.DEFAULT_RESOLUTION, tracks);
// 4. Write the MIDI data to a file
File output = new File("/sdcard/example.mid");
try {
midi.writeToFile(output);
} catch(IOException e) {
Log.e(getClass().toString(), e.getMessage(), e);
}
try {
player.setDataSource(output.getAbsolutePath());
player.prepare();
} catch (Exception e) {
Log.e(getClass().toString(), e.getMessage(), e);
}
player.start();
}
@Override
protected void onDestroy() {
player.stop();
player.release();
super.onDestroy();
}
}
I figured out that this delay depends on first param in NoteOn constructor (maybe NoteOff too). I don’t understand what is 480 number is. I tried to change this number, and than less this number than shorter delay before track, BUT whole track is shorter to.
Seems like time between notes with 480 value is fine for me, but I don’t need a delay before them.
Help me please!
Ok, I figured out what is the problem.
According to this url http://www.phys.unsw.edu.au/jw/notes.html MIDI values for piano for example starts from 21. So if I start cycle from 0, then first 20 values won’t play anything.
Now about delay.
The cycle should look like this:
Delay means at what time note should be played. So if we want to play all notes one by one, we need to set delay as sum of all previous notes duration.