Mp3agic is a lightweight, 100% Java library designed to handle MP3 files and their metadata. It provides developers with a straightforward way to read and write ID3v1 and ID3v2 tags, as well as low-level MPEG frame data. Getting Started with Mp3agic
To use mp3agic in your project, you first need to include it as a dependency. The library is widely available through Maven Central.
Use code with caution. Reading MP3 Metadata
Reading metadata involves loading an MP3 file into an Mp3File object and then checking for the presence of specific tag versions.
import com.mpatric.mp3agic.; public class ReadMetadata { public static void main(String[] args) throws Exception { Mp3File mp3file = new Mp3File(“example.mp3”); // General information System.out.println(“Length: ” + mp3file.getLengthInSeconds() + “ seconds”); System.out.println(“Bitrate: ” + mp3file.getBitrate() + “ kbps”); // Reading ID3v1 tags if (mp3file.hasId3v1Tag()) { ID3v1 id3v1Tag = mp3file.getId3v1Tag(); System.out.println(“Artist: ” + id3v1Tag.getArtist()); System.out.println(“Title: ” + id3v1Tag.getTitle()); } // Reading ID3v2 tags (more comprehensive) if (mp3file.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3file.getId3v2Tag(); System.out.println(“Album: ” + id3v2Tag.getAlbum()); System.out.println(“Year: ” + id3v2Tag.getYear()); System.out.println(“Lyrics: ” + id3v2Tag.getLyrics()); // Accessing album art byte[] albumArt = id3v2Tag.getAlbumImage(); if (albumArt != null) { System.out.println(“Mime type: ” + id3v2Tag.getAlbumImageMimeType()); } } } } Use code with caution. Writing MP3 Metadata
Writing or updating tags is a two-step process: you modify the tag object and then call save() to create a new file with the changes.
import com.mpatric.mp3agic.; public class WriteMetadata { public static void main(String[] args) throws Exception { Mp3File mp3file = new Mp3File(“original.mp3”); ID3v2 id3v2Tag; // Use existing tag or create a new one if (mp3file.hasId3v2Tag()) { id3v2Tag = mp3file.getId3v2Tag(); } else { id3v2Tag = new ID3v24Tag(); mp3file.setId3v2Tag(id3v2Tag); } // Setting metadata fields id3v2Tag.setArtist(“New Artist”); id3v2Tag.setTitle(“New Title”); id3v2Tag.setAlbum(“New Album”); id3v2Tag.setYear(“2024”); id3v2Tag.setGenre(13); // 13 is “Pop” in ID3 standard // Adding lyrics id3v2Tag.setLyrics(“Song lyrics go here…”); // Saving the changes to a new file mp3file.save(“updated_example.mp3”); } } Use code with caution. Advanced Features
Embedded Images: Mp3agic allows you to read and write embedded cover art. You can use setAlbumImage(byte[] imageData, String mimeType) to add images.
Custom Tags: For frames not yet supported by convenience methods, users can extend the AbstractID3v2Tag class to handle specific ID3v2 frames.
VBR Support: The library can accurately calculate the length of Variable Bit Rate (VBR) files by scanning the actual MPEG frames.
For more detailed examples and the source code, you can visit the Official mp3agic GitHub repository.
Leave a Reply