java midi延迟

时间:2012-01-29 23:46:22

标签: java device midi latency javasound

我正在尝试创建一个能够在检测到midi设备后在计算机上播放笔记的java应用程序。

一旦我得到所需的midi设备,我就会设置接收器,设备的发送器将发送MIDI信息。

    device.getTransmitter().setReceiver( new MyReceiver()) ; 

类MyReceiver看起来像:

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() {}
}

当我运行我的代码并开始在我的midi设备上播放时,我的延迟时间很长(我无法立即听到音符)。

如何解决此问题?

2 个答案:

答案 0 :(得分:5)

由于平台上的音频支持有限,这个问题可能是不可避免的 - 例如,Windows无法通过常用的音频API提供低延迟,因此VM也无法实现。< / p>

OS X和Linux通常都可以,但如果您调整系统音频设置/驱动程序,可能会更快。

Windows上似乎存在一种解决方法(http://www.jsresources.org/faq_misc.html#asio),但我还没试过......

答案 1 :(得分:3)

我正在使用JAsioHost使用asio驱动程序的proyect来避免延迟