How can I determine that a particular file (which may or may not have an ".mp3" file extension) is in fact an MP3 file? I wish to do this in C#.
Asked
Active
Viewed 6,974 times
7
-
2C# and file type magic numbers; possibly a duplicate of http://stackoverflow.com/questions/1654846/in-c-how-can-i-know-the-file-type-from-a-byte – kagali-san Sep 04 '11 at 22:10
-
1If you successfully load it using the solution provided in http://stackoverflow.com/questions/184683/, you might consider it a valid MP3 – Merlyn Morgan-Graham Sep 04 '11 at 22:11
5 Answers
17
According to http://www.garykessler.net/library/file_sigs.html an mp3 file will always start with ID3 (hex 49 44 33) However, presence of these bytes only mean that the file is tagged with ID3 information. If this signature is not found, it could be an untagged mp3 file. To determine this, check out the mp3 file structure and you'll see that an mp3 frame starts with the signature ff fb (hex).
So :
- if file starts with hex
49 44 33
or
- if file starts with hex
ff fb
it's safe to assume that it's an MP3.

fvu
- 32,488
- 6
- 61
- 79
5
Files often start with a "magic number" to identify the data format. Depending on the format, a file starts with a certain sequence of bytes which is unique to that format. There's no standard to follow so it's not 100% reliable.
As fvu says, the mp3 magic number is 0x49 0x44 0x33

Rob Agar
- 12,337
- 5
- 48
- 63
5
- using file extension is not reliable.
- the best libary you can use is https://github.com/mono/taglib-sharp it detects most of the common file types. maybe you just want mp3, so you can extract any mp3 related class.
- a simpler library you can use is https://github.com/judwhite/IdSharp

unruledboy
- 2,455
- 2
- 23
- 30
-2
C# code:
bool isMP3(byte[] buf)
{
if (buf[0] == 0xFF && (buf[1] & 0xF6) > 0xF0 && (buf[2] & 0xF0) != 0xF0)
{
return true;
}
return false;
}