31

How do I get a sound file's total time in Java?

--UPDATE

Looks like this code does de work: long audioFileLength = audioFile.length();

    recordedTimeInSec = audioFileLength / (frameSize * frameRate);

I know how to get the file length, but I'm not finding how to get the sound file's frame rate and frame size... Any idea or link?

-- UPDATE

One more working code (using @mdma's hints):

    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
    AudioFormat format = audioInputStream.getFormat();
    long audioFileLength = file.length();
    int frameSize = format.getFrameSize();
    float frameRate = format.getFrameRate();
    float durationInSeconds = (audioFileLength / (frameSize * frameRate));
The Student
  • 27,520
  • 68
  • 161
  • 264

2 Answers2

40

Given a File you can write

File file = ...;
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat format = audioInputStream.getFormat();
long frames = audioInputStream.getFrameLength();
double durationInSeconds = (frames+0.0) / format.getFrameRate();  
mdma
  • 56,943
  • 12
  • 94
  • 128
  • I don't what's wrong, but with a file of 18 seconds your code produce a result 149120 while the new code I posted in the question produce 18.64275 (the correct size in seconds). Anyway, I wouldn't have done this without the hints, thanks! – The Student Jun 10 '10 at 15:17
  • @mdma : can you please help me in my question http://stackoverflow.com/questions/29115389/how-can-i-modify-the-pitch-of-an-audio-file-at-different-time-instants-in-java – POOJA GUPTA Mar 18 '15 at 07:17
  • com.sun.media.sound.RIFFInvalidDataException: Chunk size too big, https://bugs.openjdk.java.net/browse/JDK-8132782 – Frank R. May 02 '18 at 02:48
-1

This is a easy way:

FileInputStream fileInputStream = null;
long duration = 0;

try {
    fileInputStream = new FileInputStream(pathToFile);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

try {
    duration = Objects.requireNonNull(fileInputStream).getChannel().size() / 128;
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(duration)