Alexandre Bourget

geek joy

Archives for May 2009

pyogg, pyvorbis and massively tagging your ogg files

May 26, 2009 at 11:20 PM

UPDATE: I've since found tagpy which is snappy fast, and reads/writes tags for a whole bunch of formats. Be careful, it can cause some confusion with the namespace ogg.vorbis, however, you can use it with the tagpy.ogg.vorbis namespace.

I was looking for a simple way to massively tag some .ogg files using my favourite scripting language.

At first, it wasn't obvious which things could be used to just add some track artists, albums and title informations, so here are my findings:

To open an ogg vorbis file, and get it's comments, run:

>>> import ogg.vorbis
>>> vf = ogg.vorbis.VorbisFile('/tmp/test.ogg')
>>> vc = vf.comments()

You'll then have the VorbisComment object in the vc variable.

Because vorbis files can handle more than one value for each tag (each key of a simili-dict), all tags return a list. You can see what happens with:

>>> vc.as_dict()
{'VENDOR': ['Xiph.Org libVorbis I 20070622'],
 'ARTIST': ['test artist'],
 'ALBUM': ['test album'],
 'TITLE': ['test title']}

See the v-comment specs at for a list of useful tags.

Now, if you need to modify tags, you'll need to create a new VorbisComment() object and copy the existing comments/tags taken from the original file:

>>> nc = ogg.vorbis.VorbisComment()
>>> for x in vc.items()
...     if x[0] in ['ARTIST', 'ALBUM', 'TITLE', 'VENDOR']:
...         nc.add_tag(x[0], x[1].encode('utf-8'))
>>> nc.add_tag('CUSTOM_TAG', 'mega-comment')

You can pose any condition in there to match the tag x[0] you need to copy or hold.

Note that you should call .add_tag() with a 'str' as second parameter, as giving it a 'unicode' object encodes as doubled UTF-8 or crashes, not sure why.

Once you're ready, write your new comments to file, with either .append_to() -- which will (not so) obviously append the comments to the file -- or .write_to(), as in the example:

>>> nc.write_to('/tmp/test.ogg')

Now the output of vorbiscomment -l /tmp/test.ogg will read:

$ vorbiscomment -l /tmp/test.ogg 
VENDOR=Xiph.Org libVorbis I 20070622
ARTIST=test artist
ALBUM=test album
TITLE=test title

and mplayer will say:

Ogg file format detected.
Clip info:
 Artist: test artist
 Album: test album
 Name: test title

Not very pythonic, but still works.

Read and Post Comments