Reputation: 989
I'm trying to write a music app capable of playing MIDI files in sync with user input. I've got as far as creating a custom view, playing sounds, and reading MIDI data. I run the playback of MIDI data in the view's onDraw() method so I can apply user input to it. The note data is stored as an array of note pitches and times to play measured in ms from the start.
My test data plays a note of a different pitch every 500 ms (half a second). I log the currentThreadTimeMillis() alongside the time interval for each note, and it is as I expect. Every 500 ticks with a small variation, a note is played. However, this count in ms is about half real-world speed, taking a second to count 500 ms! I am running on a Galaxy Ace so this isn't an issue of a slow emulator.
How come SystemClock.currentThreadTimeMillis() is taking a good two seconds to count 1000ms?
public void onDraw(Canvas canvas) {
// TODO : Draw notes
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(aNote.img, aNote.x, aNote.y, null);
if (ready>0){
elapsed_time = SystemClock.currentThreadTimeMillis() - start_time;
midi_note_data = MIDI.track_data.get(current_note);
if (midi_note_data.start_time <= elapsed_time){
current_note++;
pitch = midi_note_data.pitch;
Log.d("MUSIC", "Note time " + midi_note_data.start_time + " ThreadTime "+ elapsed_time);
sounds.play(tone, 1.0f, 1.0f, 0, 0, notes[pitch]);
}
if (current_note > MIDI.track_data.size()-1){
ready = -2;
}
}else if (ready == 0){
start_time = SystemClock.currentThreadTimeMillis();
Log.d("MUSIC", "Start time "+start_time);
ready = 1;
}
}
Upvotes: 3
Views: 3819
Reputation: 3550
You are using SystemClock.currentThreadTimeMillis(), which is the amount of time that the current thread has been running for. On Android, I'm guessing the UI thread is only actually running half of the time. (the other half is for the rest of the operating system!)
Switch to System.currentTimeMillis() and your problems will be solved.
You can read more about the different time measuring systems here.
Upvotes: 5