jAudiotagger - How to create custom TXXX tags

Pwdr picture Pwdr · Nov 17, 2011 · Viewed 8.9k times · Source

I want to create/add a custom ID3 tag to a MP3 (ID3v2.3 or ID3v2.4). There is a TXXX tag for this purpose, but I don't know how to create it using the library jAudiotagger.

Answer

Pwdr picture Pwdr · Nov 18, 2011

Just found out myself, the following code is not properly tested / not clean but does the task:

/**
 * This will write a custom ID3 tag (TXXX).
 * This works only with MP3 files (Flac with ID3-Tag not tested).
 * @param description The description of the custom tag i.e. "catalognr"
 * There can only be one custom TXXX tag with that description in one MP3 file
 * @param text The actual text to be written into the new tag field
 * @return True if the tag has been properly written, false otherwise
 */

public boolean setCustomTag(AudioFile audioFile, String description, String text){
    FrameBodyTXXX txxxBody = new FrameBodyTXXX();
    txxxBody.setDescription(description);
    txxxBody.setText(text);

    // Get the tag from the audio file
    // If there is no ID3Tag create an ID3v2.3 tag
    Tag tag = audioFile.getTagOrCreateAndSetDefault();
    // If there is only a ID3v1 tag, copy data into new ID3v2.3 tag
    if(!(tag instanceof ID3v23Tag || tag instanceof ID3v24Tag)){
        Tag newTagV23 = null;
        if(tag instanceof ID3v1Tag){
            newTagV23 = new ID3v23Tag((ID3v1Tag)audioFile.getTag()); // Copy old tag data               
        }
        if(tag instanceof ID3v22Tag){
            newTagV23 = new ID3v23Tag((ID3v11Tag)audioFile.getTag()); // Copy old tag data              
        }           
        audioFile.setTag(newTagV23);
    }

    AbstractID3v2Frame frame = null;
    if(tag instanceof ID3v23Tag){
        frame = new ID3v23Frame("TXXX");
    }
    else if(tag instanceof ID3v24Tag){
        frame = new ID3v24Frame("TXXX");
    }

    frame.setBody(txxxBody);

    try {
        tag.addField(frame);
    } catch (FieldDataInvalidException e) {
        e.printStackTrace();
        return false;
    }

    try {
        audioFile.commit();
    } catch (CannotWriteException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}