I am developing a Unity game that relies on MIDI input from a piano keyboard, using the DryWetMIDI library. I have to detect when a chord has been played and process the chord as a whole.
Currently, my approach is to wait for 0.1 seconds after the first note press, and put all notes pressed during this period into a list. Then I process this list. However, when I attempt this with Coroutine, the code inside WaitThenNotify() never executes.
Here is the code.
private List<NoteOnEvent> inputs = new List<NoteOnEvent>();
private bool waiting = false;
// Start is called before the first frame update
void Start() {
if ((InputDevice.GetAll() is null)) {
return;
}
inputDevice = InputDevice.GetById(0);
inputDevice.EventReceived += OnEventReceived;
inputDevice.StartEventsListening();
}
private void OnEventReceived(object sender, MidiEventReceivedEventArgs e) {
if (e.Event.EventType.Equals(MidiEventType.NoteOn)) {
inputs.Add((NoteOnEvent)e.Event);
}
if (!waiting) {
// catch all inputs within 0.1 seconds, for chords.
waiting = true;
StartCoroutine(WaitThenNotify());
}
}
IEnumerator WaitThenNotify() {
yield return new WaitForSeconds(0.1f);
print("here");
PianoPressObserver.UpdateSubjects(inputs);
waiting = false;
inputs.Clear();
}
Can anyone inform me as to why this happens? Or better yet, is there a better way of catching chord inputs?