Posts Tagged ID3
Reading ID3 Tags using C#
Posted by eric in C# Programming, General Programming on February 21, 2007
I’m currently working on an application which will read through a directory full of MP3′s downloaded from USENET and then sort them into sub-folders titled after the “Artists – Album” stored within the ID3 tag.
I currently only have code that can read ID3v1 tags but am working on updated code which will allow for ID3v2+ tags to be read as well.
I use a STRUCT to hold the ID3 data and then use a quick little routine to parse the raw byte[] array containing the ID3 data read from the file into my STRUCT.
The STRUCT:
[csharp]
private struct ID3Tag
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public byte[] bTagHeader; //0-2
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]
public byte[] bTrackName; //3-32
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]
public byte[] bArtistsName; //33-62
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]
public byte[] bAlbumName; //63-92
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] bYear; //93-96
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]
public byte[] bComment; //97-126
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public byte[] bGenres; //127
}
[/csharp]
Reading the last 128 bytes of the MP3 file into a byte[] array:
[csharp]
private byte[] ReadID3FromFileToByte(string sLocalFile)
{
using (FileStream oFS = new FileStream(sLocalFile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader oBR = new BinaryReader(oFS))
{
oBR.BaseStream.Position = (oFS.Length – 128);
return oBR.ReadBytes((int)oFS.Length);
}
}
}
[/csharp]
The routine used to convert by the byte[] array into the STRUCT:
[csharp]
private ID3Tag ID3BytesToID3Struct(byte[] bRawID3)
{
GCHandle hRawID3 = GCHandle.Alloc(bRawID3, GCHandleType.Pinned);
ID3Tag id3NewTag = (ID3Tag)Marshal.PtrToStructure((hRawID3.AddrOfPinnedObject()), typeof(ID3Tag));
hRawID3.Free();
return id3NewTag;
}
[/csharp]
And the code which brings it all together:
[csharp]
byte[] bFileData = ReadID3FromFileToByte(sMyInputFile);
ID3Tag myID3 = ID3BytesToID3Struct(bFileData);
[/csharp]
I hope this is able to help someone else out in their efforts to read an ID3 tag using C#.
Cheers!


