Zax
Zax

Reputation: 199

Function to write id3 tag with python 3 mutagen

In order to modify an id3 tag value with mutagen - let's say the track number (TRCK) - I found this:

filename = '/myDir/myFile.mp3'
from mutagen.mp3 import MP3
audio = MP3(fileName)
from mutagen.id3 import ID3NoHeaderError, ID3, TRCK
try: 
    audio = ID3(fileName)
except ID3NoHeaderError:
    print("Adding ID3 header")
    audio = ID3()
audio['TRCK'] = TRCK(encoding=3, text=5)

But I don't understand how could I make a function to modify passed tag, something like:

def writeTag(filename, tagName, newValue):
     from mutagen.mp3 import MP3
     audio = MP3(fileName)
     ... ???

writeTag('/myDir/myFile.mp3', 'TRCK', 5)

Upvotes: 2

Views: 2656

Answers (1)

user6223604
user6223604

Reputation:

If you want to edit ID3 tags directly, use the ID3 module.

from mutagen.id3 import ID3, TIT2

path = 'example.mp3'
tags = ID3(path)
print(tags.pprint())

tags.add(TIT2(encoding=3, text="new_title"))
tags.save()

**For information : The tag IDs are summarized in the official documentation at the following link.

It may be easier to use the pprint() method to display the ID3 tags like :

song titles (TIT2)
Album name (TALB)

[EDIT] As below an example for all tag id with specific function :

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

def writeTag(filename, tagName, newValue):
        #title
        if (tagName == 'TIT2'):
            tags["TIT2"] = TIT2(encoding=3, text=u''+newValue+'')
        #mutagen Album Name
        elif (tagName == 'TALB'):
            tags["TALB"] = TALB(encoding=3, text= u''+newValue+'')
        #mutagen Band
        elif (tagName == 'TPE2'):
            tags["TPE2"] = TPE2(encoding=3, text= u''+newValue+'')
        #mutagen comment
        elif (tagName == 'COMM'):
            tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=u''+newValue+'')
        #mutagen Artist
        elif (tagName == 'TPE1'):
            tags["TPE1"] = TPE1(encoding=3, text=u''+newValue+'')
        #mutagen Compose   
        elif (tagName == 'TCOM'):           
            tags["TCOM"] = TCOM(encoding=3, text=u''+newValue+'')
        #mutagen Genre
        elif (tagName == 'TCON'):
            tags["TCON"] = TCON(encoding=3, text=u''+newValue+'')
        #mutagen Genre date
        elif (tagName == 'TDRC'):
            tags["TDRC"] = TDRC(encoding=3, text=u''+newValue+'')
        #track_number    
        elif (tagName == 'TRCK'):
            tags["TRCK"] = TRCK(encoding=3, text=u''+newValue+'')
    
path = 'example.mp3'
tags = ID3(path)
writeTag(path,"TIT2","NewValue")
tags.save(path)

Upvotes: 4

Related Questions