Does anyone have good examples of using mutagen to write to files?

YGA picture YGA · Oct 28, 2010 · Viewed 26.2k times · Source

Just as the title asks — does anyone have a good example of using the Mutagen Python ID3 library to write to .mp3 files?

I'm looking, in particular, to add disc/track number information, but examples editing the title and artist would be helpful as well.

Cheers,
/YGA

Answer

ccpizza picture ccpizza · Dec 26, 2012

Taken from a script I made a while ago for embedding lyrics into MP3 files:

http://code.activestate.com/recipes/577138-embed-lyrics-into-mp3-files-using-mutagen-uslt-tag/

The relevant part is:

from mutagen.id3 import ID3NoHeaderError
from mutagen.id3 import ID3, TIT2, TALB, TPE1, TPE2, COMM, TCOM, TCON, TDRC, TRCK

# Read the ID3 tag or create one if not present
try: 
    tags = ID3(fname)
except ID3NoHeaderError:
    print("Adding ID3 header")
    tags = ID3()

tags["TIT2"] = TIT2(encoding=3, text=title)
tags["TALB"] = TALB(encoding=3, text=u'mutagen Album Name')
tags["TPE2"] = TPE2(encoding=3, text=u'mutagen Band')
tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=u'mutagen comment')
tags["TPE1"] = TPE1(encoding=3, text=u'mutagen Artist')
tags["TCOM"] = TCOM(encoding=3, text=u'mutagen Composer')
tags["TCON"] = TCON(encoding=3, text=u'mutagen Genre')
tags["TDRC"] = TDRC(encoding=3, text=u'2010')
tags["TRCK"] = TRCK(encoding=3, text=u'track_number')

tags.save(fname)

See also: