title: Java, bytes read by TargetDataLine, Bad code saving its bytes to file
body: <p>I need to perform <strong>Digital Signal Processing</strong> over the Sound captured by Microphone.</p>
  
  <p>For this reason I made a Java Program, the Sound saved using <code>AudioSystem.write</code> works like expected, but I need to perform the 
  processing the sound on the fly. That is, without storing it in file, for which I want to take the bytes (of the sound) captured by the microphone and process them directly.
  After writing my application I noticed that I did not get the expected behavior, so I chose to store the captured bytes to Disk, and compare it as <code>AudioSystem.write</code> stores it, and I noticed that the bytes (payload, without the WAV header) between both different files.</p>
  
  <p>The code related to <code>BlockingQueue</code> is because I want to use it, and some commented codes is because I was testing if I had made a mistake.
  The frequency/sampleRate <strong><code>8192</code></strong>, is what I should use.</p>
  
  <p>Actually using <code>AudioSystem.write</code> <strong>is not an option</strong> because I would spend a lot of time writing and rereading the disc. I used it to corroborate the bytes I was working with.</p>
  
  <pre><code>public class CatchingSoundBytes {
  
    public static void main(String[] args) {
  
      try {
        new CatchingSoundBytes().executor();
      } catch (LineUnavailableException ex) {
        ex.printStackTrace();
      }
    }
  
    public void executor() throws LineUnavailableException {
      int numChannels = 1;
      int numBytesPerSample = 2;
      int sampleRate = 8192;
      AudioFormat audioformat = new AudioFormat(sampleRate, 8 * numBytesPerSample, numChannels, true, true);
      DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioformat);
      TargetDataLine targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
      try {
        targetDataLine.open(audioformat);
        targetDataLine.start();
      } catch (LineUnavailableException ex) {
        System.out.println("ex:" + ex.getMessage());
      }
  
      int bufferSize = (int) Math.pow(2.0, 11);
      final PipedOutputStream srcSavePOStream = new PipedOutputStream();
      final PipedInputStream snkSavePIStream = new PipedInputStream(bufferSize);
      try {
        snkSavePIStream.connect(srcSavePOStream);
      } catch (IOException ex) {
        System.out.println("ex:" + ex.getMessage());
      }
  
      String dateFilename = new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date());
  
      // INI Save File
      new Thread(() -&gt; {
        AudioInputStream aisRecording = new AudioInputStream((InputStream) snkSavePIStream, audioformat, AudioSystem.NOT_SPECIFIED);
        File fileRecordedWav = new File("Rec_" + dateFilename + ".wav");
        System.out.println("fileRecordedWav:" + fileRecordedWav.getAbsolutePath());
        try {
          AudioSystem.write(aisRecording, AudioFileFormat.Type.WAVE, fileRecordedWav);
        } catch (IOException ex) {
          System.out.println("Save File -&gt; ex:" + ex.getMessage());
        }
      }).start();
      // END Save File
  
      /*
         PipedOutputStream rafPOStream = new PipedOutputStream();
         PipedInputStream rafPIStream = new PipedInputStream(bufferSize);
         try {
           rafPIStream.connect(rafPOStream);
         } catch (IOException ex) {
           System.out.println("ex:" + ex.getMessage());
         }
       */
      BlockingQueue&lt;BytesSound&gt; blockingQueue = new LinkedBlockingQueue&lt;&gt;();
      Stopper stopper = new Stopper();
      stopper.setRunning(true);
  
      // INI Capture Sound
      new Thread(() -&gt; {
        long index = 0;
        byte[] buffer = new byte[bufferSize];
        while (stopper.isRunning()) {
          try {
            int count = targetDataLine.read(buffer, 0, bufferSize);
            if (count &gt; 0) {
              byte[] output = new byte[count];
              System.arraycopy(buffer, 0, output, 0, count);
              srcSavePOStream.write(output); // Send to Save Using AudioSystem.write
              //rafPOStream.write(output);
              blockingQueue.put(new BytesSound(output, index)); // Send to Save Using RandomAccessFile
            }
          } catch (Exception ex) {
            System.out.println("Capture Sound -&gt; ex:" + ex.getMessage());
          }
          index++;
        }
        targetDataLine.stop();
        try {
          targetDataLine.close();
        } catch (SecurityException e) {
        }
      }).start();
      // END Capture Sound
  
      // INI Save RandomAccessFile File
      new Thread(() -&gt; {
        String filename = "Raf_" + dateFilename + ".wav";
        System.out.println("raf:" + filename);
        long index = 0;
        byte[] buffer = new byte[bufferSize];
        while (stopper.isRunning()) {
          try {
            BytesSound bytesSound = blockingQueue.take();
            if (bytesSound instanceof Kill) {
              break;
            }
            /*
               rafPIStream.read(buffer);
               BytesSound bytesSound = new BytesSound(buffer, index);
             */
  
            //REALLY I don't need to save bytes in this stage, 
            //only in order to compare with payload of method using AudioSystem.write
            // I need the bytes and position for processing
            RandomAccessFile raf = new RandomAccessFile(filename, "rw");
            addSample(raf, bytesSound);
          } catch (Exception ex) {
            System.out.println("Save RandomAccessFile File -&gt; ex:" + ex.getMessage());
          }
          index++;
        }
      }
      ).start();
      // END Save RandomAccessFile File
  
      new Timer(true).schedule(new TimerTask() {
        @Override
        public void run() {
          stopper.setRunning(false);
        }
      }, 4000L);
    }
  
    private void addSample(RandomAccessFile raf, BytesSound bytesSound) {
      try {
        raf.seek(bytesSound.getIndex() * bytesSound.getChunk().length);
        raf.write(bytesSound.getChunk());
      } catch (IOException ex) {
        System.out.println("ex:" + ex.getMessage());
      }
    }
  
    private class BytesSound {
  
      private final byte[] chunk;
      private final long index;
  
      public BytesSound(byte[] chunk, long index) {
        this.chunk = chunk;
        this.index = index;
      }
  
      public byte[] getChunk() {
        return chunk;
      }
  
      public long getIndex() {
        return index;
      }
  
    }
  
    private class Kill extends BytesSound {
  
      public Kill(byte[] chunk, long index) {
        super(chunk, index);
      }
    }
  
    private class Stopper {
  
      private boolean running;
  
      public boolean isRunning() {
        return running;
      }
  
      public void setRunning(boolean running) {
        this.running = running;
      }
  
    }
  
  }
  </code></pre>
  
  <p><strong>What should I change, to correctly take the bytes directly from the microphone?</strong></p>