How can I determine that a particular file is in f

2020-07-09 08:25发布

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#.

标签: c#
5条回答
我想做一个坏孩纸
2楼-- · 2020-07-09 08:55

C# code:

bool isMP3(byte[] buf)
{
    if (buf[0] == 0xFF && (buf[1] & 0xF6) > 0xF0 && (buf[2] & 0xF0) != 0xF0) 
    {
         return true;
    }
    return false;
}
查看更多
Melony?
3楼-- · 2020-07-09 09:02

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

查看更多
We Are One
4楼-- · 2020-07-09 09:13
  1. using file extension is not reliable.
  2. 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.
  3. a simpler library you can use is https://github.com/judwhite/IdSharp
查看更多
▲ chillily
5楼-- · 2020-07-09 09:13

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.

查看更多
倾城 Initia
6楼-- · 2020-07-09 09:15
string[] filePath = Directory.GetFiles(fbdialog.SelectedPath.ToString(),".mp3", 
                                       SearchOption.AllDirectories);

foreach (string str in filePath)
{
    MessageBox.Show("It's mp3 file");
}
查看更多
登录 后发表回答