0

I have currently implemented a feature which allows the user to playback the notes they have played.

Here is the code:

public void playNotes() throws InvalidMidiDataException,
        MidiUnavailableException {

    ArrayList<KeyPress> keyPressList = keyPressListCollection.getKeyPressList();
    double bpm = keyPressListCollection.getMetronome().getBpm();
    double millisPerTick = (60000.0 / (bpm * 16.0));
    double ticksPerMilli = 1 / millisPerTick;

    if (keyPressListCollection.isPlaying()) {
        sequencer.stop();
        sequencer.close();
    }

    sequencer = MidiSystem.getSequencer();
    sequencer.open();
    Sequence sequence = new Sequence(Sequence.PPQ, 16);
    Track track = sequence.createTrack();

    for (int i = 0; i < keyPressList.size(); i++) {
        KeyPress keyPress = keyPressList.get(i);

        ShortMessage noteOnMsg = new ShortMessage();
        noteOnMsg.setMessage(ShortMessage.NOTE_ON, 0, keyPress.getKeyNumber(), keyPress.getVelocity());

        ShortMessage noteOffMsg = new ShortMessage();
        noteOffMsg.setMessage(ShortMessage.NOTE_OFF, 0, keyPress.getKeyNumber(), 0);

        track.add(new MidiEvent(noteOnMsg, (long) (keyPress.getStartTime() * ticksPerMilli)));
        track.add(new MidiEvent(noteOffMsg, (long) (keyPress.getEndTime() * ticksPerMilli)));

    }

    keyPressListCollection.setPlaying(true);
    sequencer.setSequence(sequence);
    sequencer.setTempoInBPM((float) bpm);
    sequencer.start();

This works fine and play's the notes in my arraylist. However I want to be able to visually show the user what note is being played, or the position of which the playback is at.

The question is, how do I make a method call for each MidiEvent the sequencer processes?

2 Answers 2

2

I want to be able to visually show the user .. or the position of which the playback is at.

Use a JProgressBar. Set the maximum and current position according to the values obtained from Sequencer methods getMicrosecondLength() & getMicrosecondPosition().

1

You can get a great deal of control if you create "meta events" that you can use to chart your progress, and have a MetaEventListener that notifies you of your progress. It could be as simple as a "tick" for each note start.

If you query via getMicroSecondPosition or Length, the timing and accuracy of the update is determined by polling which in some circumstances can be dubious. Sometimes, it is just fine. With a MetaEventListener, the event itself it the trigger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.