I am creating an application in which the user can add several MIDI notes to the collection, from here they can click the "Play" button, and the application will iterate over each note and play them through the speakers.
I created a MIDIMessage class that contains information about the note that the user selected to add to the list, and the data is stored as Pitch, Velocity, Delay and Channel.
Each of these messages is stored in an ArrayList with a type as MIDIMessage.
Then I continue to add the collection iterator to the iterator object and play the sound until the collection has an element.
For some reason, even if I add only one note to the collection, there are always two notes playing with the same pitch, length and speed.
Also, each note is played simultaneously, regardless of how many of them are in the collection, I assumed that there would be some delay between them.
The following is the code I'm currently using:
MIDIMessage:
package javatest;
public class MIDIMessage
{
private int pitch;
private int velocity;
private int channel;
public MIDIMessage(int p, int v, int c)
{
pitch = p;
velocity = v;
channel = c;
}
public int GetPitch()
{
return this.pitch;
}
public int GetVelocity()
{
return this.velocity;
}
public int GetChannel()
{
return this.channel;
}
}
Adding a note to the collection:
public void AddToList()
{
int channel = jComboBoxChannels.getSelectedIndex();
int pitch = jComboBoxPitch.getSelectedIndex();
int velocity = ((Integer)jSpinnerVelocity.getValue());
collection.add(new MIDIMessage(pitch,velocity,channel));
}
Music Play:
try
{
jButton1.setEnabled(false);
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
Sequence sequence = new Sequence(Sequence.PPQ,1);
Track track = sequence.createTrack();
Iterator itr = collection.iterator();
int i = 0;
while(itr.hasNext())
{
MIDIMessage msg = (MIDIMessage)itr.next();
ShortMessage noteOnMsg = new ShortMessage();
noteOnMsg.setMessage(ShortMessage.NOTE_ON, msg.GetChannel(),msg.GetPitch(),msg.GetVelocity());
ShortMessage noteOffMsg = new ShortMessage();
noteOffMsg.setMessage(ShortMessage.NOTE_OFF,msg.GetChannel(),msg.GetPitch(),msg.GetVelocity());
track.add(new MidiEvent(noteOnMsg,0));
track.add(new MidiEvent(noteOffMsg,1));
}
sequencer.setSequence(sequence);
sequencer.setTempoInBPM(120);
sequencer.setLoopCount(1);
sequencer.start();
Thread.sleep(1000);
}