0

I am trying to read the cover from an MP3 file with the following code.

import tkinter as tk
from PIL import Image, ImageTk
from io import BytesIO
import mutagen
from mutagen.id3 import APIC

root = tk.Tk()
image_bytes = mutagen.File('/Users/id3-sample.mp3')['APIC:'].data 
image_stream = BytesIO(image_bytes)
img = ImageTk.PhotoImage(Image.open(image_stream))
tk.Label(root, image = img).pack() 

But I get the following error message:

File  "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mutagen/_util.py", line 536, in __getitem__
return self.__dict[key]
builtins.KeyError: 'APIC:'
Giova
  • 1,879
  • 1
  • 19
  • 27
Franc
  • 39
  • 2

2 Answers2

0

You can use Mutagen's File, Picture classes. Checkout this answer by foosion.

Shujath
  • 846
  • 1
  • 8
  • 22
0

The exception type KeyError you got, is raised by the __getitem__ method of an object of type dict when, using the syntax dictionary[key], you try to access for reading the value of a key that is not stored in the dictionary.

In your code, as pointed out by @Thierry Lathuille in the comments, you are doing that mistake. You are trying to access for reading the value of the key APIC: which is not stored into the object of type mutagen.File supporting attribute retrieval through the __getitem__ method (as dictionaries does). The correct key should be APIC.

...
image_bytes = mutagen.File('/Users/id3-sample.mp3')['APIC'].data 
...
Giova
  • 1,879
  • 1
  • 19
  • 27
  • Thanks for your comment. I have checked the mp3 file and found the APIC key: Ihttp://www.stagetwo.euageTwo AlbumTCON52TIT2Test TitelTPE1Sick^TRCK01TPE2 StageTwoTPOS1TDRC2013COMMXXXBeispiel KommentarTCOMSick^TOPENiemandWXXXhttp://www.stagetwo.euAPICFimage/jpegstagetwo-logo.jpgˇÿˇ‡JFIFˇ˛*ˇ‚ICC_PROFILElcmsmntrRGB XYZ ‹)9acspAPPLˆ÷”-lcms desc¸^cprt\wtpthbkpt| – Franc Jun 22 '19 at 08:01
  • Well, technically speaking it was an answer, not a comment and you should accept it. Anyway you're welcome! Moreover I would advise you not to post data, like you did in your comment. If you have a newer different question do not post it in comments. Thanks – Giova Jun 22 '19 at 08:31