How to read mp3 id3-tag

Djembefola

Active Member
Licensed User
Longtime User
How can i read the id3tag of mp3 files with b4a?

Is this possible from within b4a? or do i need the help of a library?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Using RandomAccessFile you can read the tags by understanding the file format: MPEG AUDIO FRAME HEADER

This code will log the fields:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   LogMp3Tags(File.DirRootExternal, "1.mp3")
End Sub

Sub LogMp3Tags(Dir As String, FileName As String)
   Dim raf As RandomAccessFile
   raf.Initialize2(Dir, FileName, True, True)
   If raf.Size < 128 Then
      Log("No TAG found.")
      Return
   End If
   Dim buffer(128) As Byte
   raf.ReadBytes(buffer, 0, 3, raf.Size - 128)
   If BytesToString(buffer, 0, 3, "UTF8") <> "TAG" Then
      Log("No TAG found.")
      Return
   End If
   'Title
   raf.ReadBytes(buffer, 0, 30, raf.CurrentPosition)
   Log("Title=" & ConvertBytesToString(buffer, 30))
   'Artist
   raf.ReadBytes(buffer, 0, 30, raf.CurrentPosition)
   Log("Artist=" & ConvertBytesToString(buffer, 30))
   'Album
   raf.ReadBytes(buffer, 0, 30, raf.CurrentPosition)
   Log("Album=" & ConvertBytesToString(buffer, 30))
   'Year
   raf.ReadBytes(buffer, 0, 4, raf.CurrentPosition)
   Log("Album=" & ConvertBytesToString(buffer, 4))
   'Comment
   raf.ReadBytes(buffer, 0, 30, raf.CurrentPosition)
   Log("Comment=" & ConvertBytesToString(buffer, 30))
   'Genre
   Dim genre As Int
   genre = raf.ReadUnsignedByte(raf.CurrentPosition)
   Log("Genre=" & genre)
End Sub

Sub ConvertBytesToString(Buffer() As Byte, MaxLength As Int) As String
   For i = 0 To MaxLength - 1
      If Buffer(i) = 0 Then Return BytesToString(Buffer, 0, i, "UTF8")
   Next
   Return BytesToString(Buffer, 0, MaxLength, "UTF8")
End Sub
 
Upvote 0
Top