1

I am trying to create a small java program to cut an audio file down to a specified length. Currently I have the following code:-

import java.util.*;
import java.io.*;
import javax.sound.sampled.*;

public class cuttest_3{

public static void main(String[]args)
    {
     int totalFramesRead = 0;

 File fileIn = new File("output1.wav");

 // somePathName is a pre-existing string whose value was
 // based on a user selection.

 try {
      AudioInputStream audioInputStream = 
      AudioSystem.getAudioInputStream(fileIn);
      int bytesPerFrame = 
      audioInputStream.getFormat().getFrameSize();
      if (bytesPerFrame == AudioSystem.NOT_SPECIFIED) {

     // some audio formats may have unspecified frame size
     // in that case we may read any amount of bytes

      bytesPerFrame = 1;
      } 

      // Set a buffer size of 5512 frames - semiquavers at 120bpm

      int numBytes = 5512 * bytesPerFrame; 
      byte[] audioBytes = new byte[numBytes];



      try {
        int numBytesRead = 0;
        int numFramesRead = 0;

        // Try to read numBytes bytes from the file.

        while ((numBytesRead = 
          audioInputStream.read(audioBytes)) != -1) {
          // Calculate the number of frames actually read.
          numFramesRead = numBytesRead / bytesPerFrame;
          totalFramesRead += numFramesRead;

          // Here,  - output a trimmed audio file

             AudioInputStream cutFile = 
                 new AudioInputStream(audioBytes);

             AudioSystem.write(cutFile, 
             AudioFileFormat.Type.WAVE, 

                new File("cut_output1.wav"));

        }
      } catch (Exception ex) { 
        // Handle the error...
      }
    } catch (Exception e) {
      // Handle the error...
    }
}
}

On attempting compilation, the following error is returned:-

cuttest_3.java:50: error: incompatible types: byte[] cannot be converted to TargetDataLine
                 new AudioInputStream(audioBytes);

I am not very familiar with AudioInputStream handling in Java, so can anyone suggest a way I can conform the data to achieve output? Many thanks

Flowso
  • 13
  • 4

1 Answers1

0

You have to tell the AudioInputStream how to decipher the bytes you pass in as is specified by Matt in the answer here. This documentation indicates what each of the parameters mean.

A stream of bytes does not mean anything until you indicate to the system playing the sound how many channels there are, the bit resolution per sample, samples per second, etc.

Since .wav files are an understood protocol and I think they have data at the front of the file defining various parameters of the audio track, the AudioInputStream can correctly decipher the 1st file you pass in.

thomas.cloud
  • 881
  • 13
  • 30
  • Thanks for that - certainly helpful. It turns out that there is a complete method for doing this here :- https://stackoverflow.com/a/7547123/9553914 – Flowso Mar 27 '18 at 13:27