tags:

views:

102

answers:

1

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));
+2  A: 

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
I'm trying to run this code, but I'm not finding how to get the sound file's frame rate. Do you have any reference on it?
Tom Brito
I've updated the code.
mdma
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!
Tom Brito
Sorry, your code is producing correct output, I was printing the wrong variable.. Thanks again!
Tom Brito