Search code examples
javanullpointerexceptionmetadatamp3

How to successfully return the metadata off of an mp3 file while avoiding a null pointer exception


When I attempt to run the program that takes the metadata and prints it from an mp3 file, I am returned with an "Exception in thread "main" java.lang.NullPointerException at project.mp3MetaData.main(musicdj.java:18)". For this class you need the jid3lib jar. How do I avoid this exception and do I need to pass any variables through the tags at the bottom?

package 1234;

import java.io.File;
import java.io.IOException;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;

public class mp3MetaData {

public static void main(String[] args) throws IOException, TagException {

    // TODO Auto-generated method stub
    File sourceFile = new     File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
    MP3File mp3file = new MP3File(sourceFile);
    ID3v1 tag = mp3file.getID3v1Tag();
    System.out.println(tag.getAlbum());
    System.out.println(tag.getAlbumTitle());
    System.out.println(tag.getTitle()); 
    System.out.println(tag.getComment());   


}

}

Any help will be greatly appreciated.


Solution

  • Your MP3 file might not contain an ID3 tag. So check whether tag is null or not, before using it. Something like this:

    public static void main(String[] args) throws IOException, TagException
    {
        File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
        final MP3File mp3file = new MP3File(sourceFile);
        final ID3v1 tag = mp3file.getID3v1Tag();
        if (null == tag)
        {
            System.out.println("No ID3 tag found!");
        }
        else
        {
            System.out.println(tag.getAlbum());
            System.out.println(tag.getAlbumTitle());
            System.out.println(tag.getTitle()); 
            System.out.println(tag.getComment());   
        }
    }