Andrew
Andrew

Reputation: 107

Mutagen: Save ID3 tag to variable

I'm trying to create an ID3 tag and save it to a variable, rather than outputting it to a file. Is there any way to do this?

This works for saving, but I can't find a way to simply save the raw bytes in a variable, without having to write out a file and then read it back in:

import mutagen
from mutagen.id3 import ID3

def no_padding(info):
    # this will remove all padding
    return 0


tags = ID3()
tags["TIT2"] = mutagen.id3.TIT2(encoding=3, text=u"Title here")
tags["TPE1"] = mutagen.id3.TPE1(encoding=3, text=u"Artist here")
tags.save('/tmp/header.id3', padding=no_padding)

Upvotes: 0

Views: 671

Answers (1)

larsks
larsks

Reputation: 311576

Just use an io.BytesIO object instead of passing a filename:

>>> import io
>>> import mutagen.id3
>>> tags = mutagen.id3.ID3()
>>> tags["TIT2"] = mutagen.id3.TIT2(encoding=3, text=u"Title here")
>>> tags["TPE1"] = mutagen.id3.TPE1(encoding=3, text=u"Artist here")
>>> buf = io.BytesIO()
>>> tags.save(buf, padding=lambda x: 0)
>>> buf.getvalue()
b'ID3\x04\x00\x00\x00\x00\x00-TIT2\x00\x00\x00\x0c\x00\x00\x03Title here\x00TPE1\x00\x00\x00\r\x00\x00\x03Artist here\x00'

Upvotes: 1

Related Questions