0

I am trying to cut an audio file into a specific portion, given the second at which to cut and how long to extend it to.

I found the code below, but as seconds are given as an int, it isn't precise.

Can anyone help me manipulate this code to allow for me to cut a wav file to the precision of a millisecond?

(i.e. i have a 10 second long audio file and I want to cut it to between 5.32 seconds and 5.55 seconds)

https://stackoverflow.com/a/7547123/5213329

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

class AudioFileProcessor {

  public static void main(String[] args) {
    copyAudio("/tmp/uke.wav", "/tmp/uke-shortened.wav", 2, 1);
  }

  public static void copyAudio(String sourceFileName, String destinationFileName, int startSecond, int secondsToCopy) {
    AudioInputStream inputStream = null;
    AudioInputStream shortenedStream = null;
    try {
      File file = new File(sourceFileName);
      AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
      AudioFormat format = fileFormat.getFormat();
      inputStream = AudioSystem.getAudioInputStream(file);
      int bytesPerSecond = format.getFrameSize() * (int)format.getFrameRate();
      inputStream.skip(startSecond * bytesPerSecond);
      long framesOfAudioToCopy = secondsToCopy * (int)format.getFrameRate();
      shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
      File destinationFile = new File(destinationFileName);
      AudioSystem.write(shortenedStream, fileFormat.getType(), destinationFile);
    } catch (Exception e) {
      println(e);
    } finally {
      if (inputStream != null) try { inputStream.close(); } catch (Exception e) { println(e); }
      if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { println(e); }
    }
  }

  public static void println(Object o) {
    System.out.println(o);
  }

  public static void print(Object o) {
    System.out.print(o);
  }

}
Community
  • 1
  • 1
Joe Corson
  • 23
  • 1
  • 5
  • you need to get it to work this is not a working program – gpasch May 23 '16 at 23:53
  • *"Can anyone help me.."* Stack Overflow is not a help desk. If you can make a reasonable attempt and show that in code, then ask a *specific* question, it might go better. – Andrew Thompson May 24 '16 at 04:23

1 Answers1

1

The format of a wav is often on the scale of 44100 frames per second. Stereo, 16-bit encoding (CD quality) gives 4 * 44100 bytes per second, or 176,400 bytes per second. A frame only consumes 1/44100th of a second, or .02 milliseconds (if my math is correct), so working with millisecond fractions of a second should not be a problem.

Simply make your inputs floats or doubles instead of ints.

In places where you multiple with either the startSecond or secondsToCopy, you will most likely need to round your answer to a multiple of 4 (or whatever the bytes per frame amount is) in order to refer to a frame boundary.

Phil Freihofner
  • 7,645
  • 1
  • 20
  • 41