I'm attempting to write a program in which audio is read from my computer's microphone, altered in some way(for now it's just to test it), then played back out through the speakers. As it is, it works fine, but there's a very noticeable delay in between when audio is input through the mic and when it can be heard, I'm trying to find a way to reduce this. I am aware that is nearly impossible for the delay to be completely removed, but I'm looking for a way to at least make it nearly inaudible.
The code is as follows:
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);
}
}
}
As it is there is a delay of what seems to be roughly 1 second, is it possible to remedy this?