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

血红的双手。 提交于 2019-12-23 20:43:26

问题


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?


回答1:


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.




回答2:


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 will be obtaining ID3 Size and Audio Bitrate from this chunk (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)



来源:https://stackoverflow.com/questions/28706093/is-it-possible-to-know-the-duration-of-an-mp3-before-the-entire-file-is-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!