Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java midi latency

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?

like image 421
Camilo Barraza Avatar asked Jan 29 '12 23:01

Camilo Barraza


2 Answers

It's possible this problem might be unavoidable due to limited audio support on your platform - for instance, Windows can't provide low latency at all through the usual audio APIs, and therefore it isn't implemented by the VM either.

OS X and Linux are generally OK but might get quicker if you tweak your system audio settings/driver.

A workaround seems to exist on Windows (http://www.jsresources.org/faq_misc.html#asio) but I haven't tried it...

like image 54
Tom Spurling Avatar answered Sep 21 '22 12:09

Tom Spurling


I´m using the JAsioHost proyect that uses an asio driver to avoid latency

like image 40
Camilo Barraza Avatar answered Sep 20 '22 12:09

Camilo Barraza