Detect if a file is an MP3 file?

微笑、不失礼 提交于 2019-11-27 14:06:50

问题


I'm writing a C++ library for decoding and encoding audio between different formats/codecs. I have a routine for quickly detecting the format before loading the required codec library.

For WAV files one can simple look for the ASCII values "RIFF" and "WAVE" at the start of the file. The same applies to FLAC, we can simply read in the first 4 bytes, which will be "fLaC".

But how can I quickly detect if a file is MP3? I can't rely on the file extension. I also can't try to decode the first MP3 frame, since there might be additional data at the start of the file (eg: ID3, cover image, etc).


回答1:


Detecting if a file is an MP3 is more complicated than searching for a fixed pattern in the file.

Some concepts

(See http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header for details)

  • MP3 file consists of a series of frames and each frame has a header at the beginning.
  • Header starts at a byte boundary with an 11-bit sync word, which is all 1s. Hence the sync word is either 0xFFE or 0XFFF.
  • Length of each frame is calculated based on the header parameters.

Algorithm to determine if a file is MP3 or not

  • Search for the sync word in the file (0xFFF or 0xFFE).
  • Parse the header parameters.
  • Determine the frame length using the header parameters.
  • Seek to the next frame using the frame length.
  • If you find another sync word after seeking, then the file is mostly an MP3 file.
  • To be sure, repeat the process to find N consecutive MP3 frames. N can be increased for a better hit-rate.



回答2:


I just check the signature like in your existing wave and flac test.
An mp3 file should have this in hex:
0x49, 0x44, 0x33
It works for some of the files I had. I'm not sure if it works in all circumstances so a more complex solution like Oak Bytes's answer may be required.



来源:https://stackoverflow.com/questions/11360286/detect-if-a-file-is-an-mp3-file

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