Search code examples
python-3.xmutagen

How to I obtain the Album picture of a music in Python?


I am trying to insert the album pictutre of a music(mp3) as an image in Python GUI window. I used mutagen ID3 picture class for this purpose. It was described in the docs but I excactly dont know how to do it. So kindly I would like to request for an example to show how to do it correctly. And if possible, please specify if there is any alternative.

Thank-you!


Solution

  • Stagger is a library for modifying id3v2 tags; it's pretty much easy to use:

    In [1]: import stagger
    
    In [2]: mp3 = stagger.read_tag('/home/gokul/Music/Linkin Park - Burning In The Skies.mp3')
    
    In [3]: mp3.artist
    Out[3]: 'Linkin Park'
    
    In [4]: mp3.album
    Out[4]: 'A Thousand Suns'
    
    In [5]: mp3.picture  # the cover has not been set yet
    Out[5]: ''
    

    Rest of the API is similar to this. You can modify tags like this:

    In [6]: mp3.album = 'Changed It'
    
    In [7]: mp3.album
    Out[7]: 'Changed It'
    

    To set the album/cover picture, all you have to do is....

    In [10]: mp3.picture = '/home/gokul/Pictures/Cover.jpg' # path to file
    
    In [11]: mp3.picture  # the cover has been saved!
    Out[11]: 'Other(0)::<2834 bytes of jpeg data>'
    

    You have to save the tags to the file now:

    In [12]: mp3.write()
    

    That's it! Done ;)
    If you want to see all the tags in the file use mp3.frames:

    In [13]: mp3.frames()
    Out[13]: 
    [TIT2(encoding=0, text=['Burning In The Skies']),
    TPE1(encoding=0, text=['Linkin Park']),
    TALB(encoding=0, text=['Changed It']),
    APIC(encoding=None, mime='image/jpeg', type=0, desc='', data=<2834 bytes of binary data b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00'...>)]
    

    Cheers!

    P.S. You can modify any id3v2 tag using stagger; some of them(most common) can be modified using a format like mp3.title = 'title'. See stagger's GitHub page for editing other(uncommon and complex) tags.