简体   繁体   中英

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

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?

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM