1

我想为 MP3(ID3v2.3 或 ID3v2.4)创建/添加自定义 ID3 标签。为此目的有一个 TXXX 标签,但我不知道如何使用库 jAudiotagger 创建它。

4

1 回答 1

2

刚刚发现自己,以下代码没有经过适当的测试/不干净,但可以完成任务:

/**
 * 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;
}
于 2011-11-18T03:15:39.637 回答