Java, байты, прочитанные TargetDataLine, неправильный код, сохраняющий свои байты в файл - PullRequest
1 голос
/ 07 ноября 2019

Мне нужно выполнить Цифровую обработку сигнала для звука, захваченного микрофоном.

По этой причине я создал программу на Java, звук, сохраненный с помощью AudioSystem.write, работает как ожидалось, ноМне нужно выполнить обработку звука на лету. То есть без сохранения его в файле, для которого я хочу взять байты (звука), захваченные микрофоном, и обработать их напрямую. После написания приложения я заметил, что не получил ожидаемого поведения, поэтому я решил сохранить захваченные байты на диск и сравнить его с AudioSystem.write, а также заметил, что байты (полезная нагрузка, без заголовка WAV)между двумя разными файлами.

Код, связанный с BlockingQueue, написан потому, что я хочу его использовать, а некоторые комментарии с комментариями - потому что я проверял, не ошибся ли я. Частота / sampleRate 8192, это то, что я должен использовать.

На самом деле использование AudioSystem.write не вариант , потому что я бы потратил много времени на написаниеи перечитываю диск. Я использовал его, чтобы подтвердить байты, с которыми я работал.

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(() -> {
      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 -> 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<BytesSound> blockingQueue = new LinkedBlockingQueue<>();
    Stopper stopper = new Stopper();
    stopper.setRunning(true);

    // INI Capture Sound
    new Thread(() -> {
      long index = 0;
      byte[] buffer = new byte[bufferSize];
      while (stopper.isRunning()) {
        try {
          int count = targetDataLine.read(buffer, 0, bufferSize);
          if (count > 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 -> ex:" + ex.getMessage());
        }
        index++;
      }
      targetDataLine.stop();
      try {
        targetDataLine.close();
      } catch (SecurityException e) {
      }
    }).start();
    // END Capture Sound

    // INI Save RandomAccessFile File
    new Thread(() -> {
      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 -> 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;
    }

  }

}

Что я должен изменить, чтобы правильно брать байты прямо с микрофона?

1 Ответ

1 голос
/ 08 ноября 2019

Подробное рассмотрение с использованием бинарного компаратора ...

enter image description here Проверьте строку 088

Я проверяю с BigEndiannessдо false. На стороне Left , которую я использовал Little Endianness, байты: B9,FF, F6, 01 для обоих файлов AIS_Lit... и RAF_Lit....

Я тестирую с BigEndianness до true. Но в правой части для файла AIS_Big... у меня есть B4, FF, 11, 02, а для файла RAF_Big... у меня есть FF, B4, 02, 11

Мне нужно изменить порядок байтов взятыхс int count = targetDataLine.read(buffer, 0, bufferSize);, когда BigEndianness равен true!

Другая вещь - это способ хранения файла размера: при использовании AudioSystem.write байты отличаются ...

enter image description here

Это означает, что bytes 5 until 8 для хранения FileSize и bytes 41 until 44 для хранения SizeData обрабатываются по-разному.

Яиспользуя для этого теста macOS Sierra (10.12) в MacBook Air , возможно , используя Windows или Linux machine с другим аппаратным обеспечением функциональность работает иначе.

Теперь мой Код решения очень прост.

boolean endianness = false;
AudioFormat audioformat = new AudioFormat(sampleRate, 8 * numBytesPerSample,
    numChannels, true, endianness);

Или используя метод исправления private byte[] endiannessReorderedBytes(byte[] incomingBytes, AudioFormat audioformat)!

Мой код завершения тестирования

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;
    boolean endianness = false;
    AudioFormat audioformat = new AudioFormat(sampleRate, 8 * numBytesPerSample, numChannels, true, endianness);
    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 = (endianness ? "Big" : "Lit") + new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date());

    // INI Save File
    new Thread(() -> {
      AudioInputStream aisRecording = new AudioInputStream((InputStream) snkSavePIStream, audioformat, AudioSystem.NOT_SPECIFIED);
      File fileRecordedWav = new File("AIS_" + dateFilename + ".wav");
      System.out.println("fileRecordedWav:" + fileRecordedWav.getAbsolutePath());
      try {
        AudioSystem.write(aisRecording, AudioFileFormat.Type.WAVE, fileRecordedWav);
      } catch (IOException ex) {
        System.out.println("Save File -> ex:" + ex.getMessage());
      }
    }).start();
    // END Save File

    BlockingQueue<BytesSound> blockingQueue = new LinkedBlockingQueue<>();
    Stopper stopper = new Stopper();
    stopper.setRunning(true);

    // INI Capture Sound
    new Thread(() -> {
      try {
        long index = 0;
        byte[] buffer = new byte[bufferSize];
        while (stopper.isRunning()) {
          try {
            int count = targetDataLine.read(buffer, 0, bufferSize);
            if (count > 0) {
              byte[] output = new byte[count];
              System.arraycopy(buffer, 0, output, 0, count);
              srcSavePOStream.write(output); // Send to Save Using AudioSystem.write
              blockingQueue.put(new BytesSound(endiannessReorderedBytes(output, audioformat), index)); // Send to Save Using RandomAccessFile
            }
          } catch (Exception ex) {
            System.out.println("Capture Sound -> ex:" + ex.getMessage());
          }
          index++;
          if (index > 1) {
            break;
          }
        }
        targetDataLine.stop();
      } catch (Exception ex) {
        System.out.println("Capture Sound -> ex:" + ex.getMessage());
      } finally {
        try {
          targetDataLine.close();
        } catch (SecurityException e) {
        }
      }
    }).start();
    // END Capture Sound

    // INI Save RandomAccessFile File
    new Thread(() -> {
      String filename = "RAF_" + dateFilename + ".wav";
      System.out.println("raf:" + filename);
      long index = 0;
      while (stopper.isRunning()) {
        try {
          BytesSound bytesSound = blockingQueue.take();
          if (bytesSound instanceof Kill) {
            break;
          }
          //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);
          raf.close();
        } catch (Exception ex) {
          System.out.println("Save RandomAccessFile File -> ex:" + ex.getMessage());
        }
        index++;
        if (index > 1) {
          break;
        }
      }
      System.out.println("Expected Size:" + index * bufferSize);
    }
    ).start();
    // END Save RandomAccessFile File

    new Timer(true).schedule(new TimerTask() {
      @Override
      public void run() {
        stopper.setRunning(false);
      }
    }, 4000L);
  }

  private byte[] endiannessReorderedBytes(byte[] incomingBytes, AudioFormat audioformat) {
    if (!(incomingBytes != null && audioformat != null)) {
      throw new IllegalArgumentException("Some arguments are null.");
    }
    byte[] outgoingBytes = new byte[incomingBytes.length];
    if (audioformat.getSampleSizeInBits() == 16) {
      if (incomingBytes.length % 2 != 0) {
        throw new IllegalArgumentException("The size of the byte array does not match the audio format.");
      }
      int count = incomingBytes.length / 2;
      if (audioformat.isBigEndian()) {
        for (int i = 0; i < count; i++) {
          outgoingBytes[i * 2] = incomingBytes[i * 2 + 1];
          outgoingBytes[i * 2 + 1] = incomingBytes[i * 2];
        }
      } else {
        System.arraycopy(incomingBytes, 0, outgoingBytes, 0, incomingBytes.length);
      }
    } else {
      if (audioformat.getEncoding() == Encoding.PCM_SIGNED) {
        for (int i = 0; i < incomingBytes.length; i++) {
          outgoingBytes[i] = (byte) (0x80 ^ incomingBytes[i]);
        }
      } else {
        System.arraycopy(incomingBytes, 0, outgoingBytes, 0, incomingBytes.length);
      }
    }
    return outgoingBytes;
  }


  private void addSample(RandomAccessFile raf, BytesSound bytesSound) {
    try {
      raf.seek(44 /*Header Length*/ + 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;
    }

  }
}
...