Hey, hey, hey
Today I saw a post on forum about reading ID3 tags from an MP3 file. Remembering rjhare's FAQ on the same subject I'd thought I would knock up a .NET version. Simply put its a single class with one method called 'ReadMP3Details' that receives the filename of the MP3 and exposes properities for the Album, Song title, Artist, etc. It opens a FileStream accessing the file and uses a BinaryReader to read the data, it navigates to the end of the file where the tag data is keep and reads the data. I suppose I could of made this class a static class and return a structure but feel free to do that yourself if that's your thing...
Enjoy - M
Public Class MP3Details
#Region "Attributes"
Private _Tag As String ' (3)
Private _Songname As String ' (30)
Private _Artist As String ' (30)
Private _Album As String ' (30)
Private _Year As String ' (4)
Private _Comment As String ' (30)
Private _Genre As String ' (1)
Private _DetailsRead As Boolean
#End Region
Public Sub New()
End Sub
Public Function ReadMP3Details(ByVal Filename As String) As Boolean
' Initialise
_DetailsRead = False
' Does the file exist?
If Not New IO.FileInfo(Filename).Exists Then
_DetailsRead = False
Return False
End If
' Reads the MP3 tag details
Dim fs As New IO.FileStream(Filename, IO.FileMode.Open, IO.FileAccess.Read)
Dim br As New IO.BinaryReader(fs)
' Move to the end of the stream - 127 places from the end...
br.BaseStream.Seek(-128, IO.SeekOrigin.End)
' Begin reading the data
_Tag = br.ReadChars(3)
' Does a tag exist?
If _Tag = "TAG" Then
' Read the rest of the data
_Songname = br.ReadChars(30)
_Artist = br.ReadChars(30)
_Album = br.ReadChars(30)
_Year = br.ReadChars(4)
_Comment = br.ReadChars(30)
_Genre = br.ReadChars(1)
_DetailsRead = True
Else
_DetailsRead = False
End If
' Cleanup
br.Close()
fs.Close()
br = Nothing
fs = Nothing
' Return value
Return _DetailsRead
End Function
#Region "Properities"
Public ReadOnly Property Songname() As String
Get
If _DetailsRead Then Return Me._Songname.ToString
End Get
End Property
Public ReadOnly Property Artist() As String
Get
If _DetailsRead Then Return Me._Artist.ToString
End Get
End Property
Public ReadOnly Property Album() As String
Get
If _DetailsRead Then Return Me._Album.ToString
End Get
End Property
Public ReadOnly Property Year() As String
Get
If _DetailsRead Then Return Me._Year.ToString
End Get
End Property
Public ReadOnly Property Comment() As String
Get
If _DetailsRead Then Return Me._Comment.ToString
End Get
End Property
Public ReadOnly Property Genre() As String
Get
If _DetailsRead Then Return Me._Genre.ToString
End Get
End Property
#End Region
End Class