コンピューターのマイクからオーディオを読み取り、何らかの方法で変更して (今はテストするだけです)、スピーカーから再生するプログラムを作成しようとしています。そのままでは問題なく動作しますが、音声がマイクから入力されてから聞こえるまでの間に非常に顕著な遅延があるため、これを減らす方法を見つけようとしています. 遅延を完全に取り除くことはほとんど不可能であることは承知していますが、少なくともほとんど聞こえないようにする方法を探しています.
コードは次のとおりです。
package com.funguscow;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class Listen {
public static void main(String[] args){
AudioFormat format = new AudioFormat(44100, 16, 2, true, true); //get the format for audio
DataLine.Info targetInfo = new DataLine.Info(TargetDataLine.class, format); //input line
DataLine.Info sourceInfo = new DataLine.Info(SourceDataLine.class, format); //output line
try {
TargetDataLine targetLine = (TargetDataLine) AudioSystem.getLine(targetInfo);
targetLine.open(format);
targetLine.start();
SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(sourceInfo);
sourceLine.open(format);
sourceLine.start();
int numBytesRead;
byte[] targetData = new byte[sourceLine.getBufferSize()];
while (true) {
numBytesRead = targetLine.read(targetData, 0, targetData.length); //read into the buffer
if (numBytesRead == -1) break;
for(int i=0; i<numBytesRead/2; i++){ //apply hard distortion/clipping
int j = (((targetData[i * 2]) << 8) & 0xff00) | ((targetData[i * 2 + 1]) & 0xff);
j *= 2;
if(j > 65535) j = 65535;
if(j < 0) j = -0;
targetData[i * 2] = (byte)((j & 0xff00) >> 8);
targetData[i * 2 + 1] = (byte)(j & 0x00ff);
}
sourceLine.write(targetData, 0, numBytesRead); //play
}
}
catch (Exception e) {
System.err.println(e);
}
}
}
このままだと1秒くらい遅れそうなのですが、これを改善することはできますか?