Is it possible to know the duration of an MP3 before the entire file is downloaded?
Asked Answered
H

2

6

This is a question about the file format of MP3s.

I've been hunting for a way to get an MP3 duration. Since I'm using JLayer SPI to decode the MP3 I've discovered that this is possible where the audio source is a file.

AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(source);
Long microseconds = (Long) fileFormat.properties().get("duration");
System.out.println(microseconds);

However when I take the similar code and the very same MP3 and change the source to a URL, JLayer does not provide the duration:

AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(source.toURI().toURL());
Long microseconds = (Long) fileFormat.properties().get("duration");
System.out.println(microseconds);

This is an important distinction because some of the music I want to play will be sourced from URLs not local files.

I suspect that this is due to limitations of the file format.

This leads me to a very simple question. Is it possible to know the duration of an MP3 before the entire file has been downloaded?

Hognut answered 24/2, 2015 at 20:58 Comment(0)
D
2

The answer is no. The mp3 file format doesn't have any information regarding the duration of the file. To compute the duration you would need to divide the length of the file by the bit rate. That would also explain the behavior of your library. As a workaround, if you have control of the files on the server you should be able to embed the duration in an id3 tag.

Dictator answered 24/2, 2015 at 21:14 Comment(2)
To compute the duration you would need to divide the length of the file by the bit rate. I presume this method falls flat the moment you have variable bitrate mp3s (as most are these days).Hognut
VBR files generally have a header that includes the total length of the file (in frames; 1152 samples per frame unless MPEG2, in which case it's 576). Look for Xing and VBRI format headers (they are placed in the ancillary data of the first MPEG frame...).Sedda
A
1

Yes, for CBR (Constant Bit Rate), you need to download chunk for about 1-2 MBytes* (must be larger than id3 size below)

In the header you normally could find whole file length:

Content-Length: 30079584

next step would be to obtain Audio Bitrate and ID3 Size from this chunk (with exiftool - link)

For example:

...
Audio Bitrate: 272 kbps
ID3 Size : 115419
...

And then just use this formula (example):

(30079584 - 115419) / (272 * 1000 / 8)

~ 881 seconds

where '* 1000 / 8' - is a kbit-to-bytes conversion (https://en.wikipedia.org/wiki/Bit_rate)

Anubis answered 13/4, 2018 at 10:48 Comment(1)
If I understand you correctly, you suggestion is to assume constant bitrate and there is nothing you can do to check if the bitrate is really constant.Hognut

© 2022 - 2024 — McMap. All rights reserved.