I’m programming a Java based Piano application. Everything works so far, but now I have a problem. It’s more a detail, but it’s a really bad user experience, so I can’t leave it like this.
Here is some code:
Synthesizer Setup
try {
synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
synthesizer.loadAllInstruments(synthesizer.getDefaultSoundbank());
} catch (MidiUnavailableException e) {
e.printStackTrace();
}
try {
synthReceiver = synthesizer.getReceiver();
} catch (MidiUnavailableException e) {
e.printStackTrace();
}
// load instrument's configuartion
int instrumentNumber = settings.getInteger("sound.instrument", 0);
Instrument instrument = synthesizer.getDefaultSoundbank().getInstruments()[instrumentNumber];
// Set the instrument on channel 0
ShortMessage message = new ShortMessage();
try {
message.setMessage(ShortMessage.PROGRAM_CHANGE, 0, instrumentNumber, 0);
} catch (InvalidMidiDataException ex) {
Logger.getLogger(TypePiano.class.getName()).log(Level.SEVERE, null, ex);
}
synthReceiver.send(message, -1);
synthesizer.loadInstrument(instrument);
synthesizer.getChannels()[0].programChange(instrumentNumber);
Play a note
// create the message
ShortMessage message = new ShortMessage();
try {
message.setMessage(ShortMessage.NOTE_ON, settings.getInteger("piano.instrument", 1), note, 100);
} catch (InvalidMidiDataException e) {
e.printStackTrace();
}
// send it
synthReceiver.send(message, -1);
// and update note stand
noteStand.notePlayed(note);
Now the problem is that the notes, don’t stop playing. The just don’t fade fully out. You here them and they don’t deactivate automatically. I don’t know where the problem is…
If you need more code, or something else just say it.
Would be cool to get an answer on this problem, I’m already trying to solve since more than two hours…
MIDI notes need two separate messages — a Note On message (which you’re sending) and a separate Note Off message to end the note, sometime later. To do that, you can either use an actual Note Off event type, or send another Note On for the same pitch, but with a velocity value (second byte) of zero.
Using a Note On with zero velocity is more commonly seen, because that lets the system use running status bytes, which permits the MIDI stream to be used more efficiently.