I´m trying to make a java application that is able to play notes on the computer after detecting a midi device.
Once I get the desired midi device I´m seting the receiver to which the device´s transmitter will deliver MIDI messages.
device.getTransmitter().setReceiver( new MyReceiver()) ;
class MyReceiver looks like:
public class MyReceiver implements Receiver {
MidiChannel[] channels ;
public MyReceiver (){
try {
Synthesizer synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
channels = synthesizer.getChannels();
channels[0].programChange( 22 ) ;
}catch ( Exception e ) {
e.printStackTrace() ;
}
}
public void noteOff ( int nota ) {
channels[0].noteOff(nota);
}
public void noteOn ( int nota ) {
channels[0].noteOn( nota , 100);
}
public void send(MidiMessage msg, long timeStamp ) {
byte[] b = msg.getMessage ();
String tmp = bits ( b [0] ) ;
int message = convertBits ( tmp ) ;
int note1 = convertBits ( bits ( b [ 1 ] ) ) ;
// note on in the first channel
if ( message == 144 ) {
noteOn( note1 ) ;
}
// note off in the first channel
if ( message == 128 ) {
noteOff( note1 ) ;
}
}
public String bits(byte b)
{
String bits = "";
for(int bit=7;bit>=0;--bit)
{
bits = bits + ((b >>> bit) & 1);
}
return bits;
}
public int convertBits ( String bits ) {
int res = 0 ;
int size = bits.length () ;
for ( int i = size-1 ; i >= 0 ; i -- ){
if ( bits.charAt( i ) == '1' ) {
res += 1 <<(size-i-1) ;
}
}
return res ;
}
public void close() {}
}
When I run my code and start playing on my midi device I´m getting a high latency (I can´t hear notes instantly).
How can I fix this problem?