I need to fetch an audio's duration from the audio's URL in java, but not able to find the way to do it. Can anyone please suggest how to do it?
Asked
Active
Viewed 659 times
2 Answers
0
I think that should do it:
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new URL("http://www.url.com/"+ args[0] +".mp3"));
AudioFormat format = audioInputStream.getFormat();
long audioFileLength = file.length();
int frameSize = format.getFrameSize();
float frameRate = format.getFrameRate();
float durationInSeconds = (audioFileLength / (frameSize * frameRate));

guygrinberger
- 327
- 2
- 14
-
1What is `file` here? The code is reading a stream not a file. In any case for a compressed file like mp3 using the file length and frame size will give the wrong answer as the frames are compressed in the file. – greg-449 Aug 14 '18 at 08:26
0
I had found the answer to this question after some research, posting the answer so that, others can do that too.
String filePrefix = FileUtils.getTempDirectoryPath() + File.separator;
URL audioURL = new URL(url);
File destination = new File(filePrefix + UUID.randomUUID().toString()); // To store the file at a certain destination for temporary usage
FileUtils.copyURLToFile(audioURL, destination);
IsoFile isoFile = new IsoFile(destination.getAbsolutePath());
double lengthInSeconds = (double)
isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
try {
System.out.println("Length of audio in seconds === " + lengthInSeconds);
destination.delete();
} catch (Exception e) {
e.printStackTrace();
}
NOTE : FileUtils from apache.commons repository, IsoFile from coremedia.iso repository

Akshay Bhardwaj
- 21
- 3