我正在尝试编写一个程序,其中从计算机的麦克风中读取音频,以某种方式进行更改(现在只是为了测试它),然后通过扬声器播放出来。事实上,它工作得很好,但是在通过麦克风输入音频和可以听到音频之间有一个非常明显的延迟,我正试图找到一种方法来减少这种延迟。我知道要完全消除延迟几乎是不可能的,但我正在寻找一种至少让它几乎听不见的方法。
代码如下:
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 秒的延迟,是否有可能解决这个问题?