Search code examples
pythonid3mutagen

Reading/writing mp3 comment tag in Python


I'm struggling with reading/writing mp3 comment tag in Python. Partly I can't read the comment values I expected. Or when setting new comments it seems that the comment is not saved to the mp3 file.

e.g. with eyed3 I tried:

mp3 = eyed3.load(filename)
comments = mp3.tag.comments
mp3.tag.comments.set("comment set with eye3d")
mp3.tag.save()

Afterwards I couldn't see the comment when checking in VLC.


Solution

  • First, I learnt that a mp3 file can have multiple comments and there's a language defined for each comment. Many tools don't show that and are not reliable. I found the executable of eyeD3 very useful tough:

    $ eyeD3 ./Frank\ Sinatra\ -\ My\ Way.mp3 
    /home/Frank Sinatra - My Way.mp3             [ 4.20 MB ]
    --------------------------------------------------------------------------------
    Time: 02:48 MPEG1, Layer III    [ ~209 kb/s @ 48000 Hz - Stereo ]
    --------------------------------------------------------------------------------
    ID3 v2.4:
    title: My Way
    artist: Frank Sinatra
    album: My Way
    track:      
    Publisher/label: 
    Comment: [Description: ] [Lang: XXX]
    That's a comment entered in VLC
    UserTextFrame: [Description: TRACKTOTAL]
    
    --------------------------------------------------------------------------------
    

    Then I realized you've got to watch for the comment's language when reading or changing comments. The library eyed3 uses language 'eng' by default. You can pass a language parameter when setting the comment like below. But it's got to be a number and thus this was not useful for me.

    mp3.tag.comments.set("comment set with eye3d","",b'1')
    

    The library mutagen doesn't know the comment tag out-of-the-box, but you can easily register it as Travis Cardwell explains in his blog. There you can specify the language value as parameter for register_tag_comment. You can pass values like 'eng' or also 'XXX'. That did the trick for me.

    register_tag_comment("XXX")
    try:
        tag = EasyID3(entry.path)
    except:
        tag = mutagen.File(path, easy=True)
        tag.add_tags()
    comment = tag['comment']
    tag['comment'] = ["comment set with mutagen"]
    tag.save()
    

    By the way, I noticed that VLC uses language 'XXX' when saving a new comment. However, it also shows e.g. 'eng' comments and can change them.