Echo when recording and playing sound

Viewed 73

I have a simple application that starts recording from the microphone and then immediately plays the sounds back to my headphones, however the problem here is: the sound quality is not good and there is a lasting echo after speaking something in the microphone which can last up to 5 seconds after speaking. I'm not sure whether the problem lies in the Java Sound API and I need to switch to another library.

I also want to mention that I use a headphone that is plugged into my computer. When I use low volume then the sound plays normal however when I turn it up to 90% of my maximum value the sound quality really becomes bad.

Here is my code:

AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false);
    
    DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, format);
    TargetDataLine mic = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
    mic.open();
    mic.start();
    
    DataLine.Info dataLineInfo2 = new DataLine.Info(SourceDataLine.class, format);
    SourceDataLine speakers = (SourceDataLine) AudioSystem.getLine(dataLineInfo2);
    speakers.open();
    speakers.start();
    
    byte[] buffer = new byte[1024];
    
    
    while(true) {
        mic.read(buffer, 0, buffer.length);
        
        speakers.write(buffer, 0, buffer.length);
        
    }
0 Answers
Related