Example #1
0
  /** Save the double array as a sound file (using .wav or .au format). */
  public static void save(String filename, double[] input) {
    // assumes 44,100 samples per second
    // use 16-bit audio, mono, signed PCM, little Endian
    AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
    byte[] data = new byte[2 * input.length];
    for (int i = 0; i < input.length; i++) {
      int temp = (short) (input[i] * MAX_16_BIT);
      data[2 * i + 0] = (byte) temp;
      data[2 * i + 1] = (byte) (temp >> 8);
    }

    // now save the file
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(data);
      AudioInputStream ais = new AudioInputStream(bais, format, input.length);
      if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
        AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
      } else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
        AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
      } else {
        throw new RuntimeException("File format not supported: " + filename);
      }
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
    }
  }