Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutagen: how to detect and embed album art in mp3, flac and mp4

I'd like to be able to detect whether an audio file has embedded album art and, if not, add album art to that file. I'm using mutagen

1) Detecting album art. Is there a simpler method than this pseudo code:

from mutagen import File
audio = File('music.ext')
test each of audio.pictures, audio['covr'] and audio['APIC:']
    if doesn't raise an exception and isn't None, we found album art

2) I found this for embedding album art into an mp3 file: How do you embed album art into an MP3 using Python?

How do I embed album art into other formats?

EDIT: embed mp4

audio = MP4(filename)
data = open(albumart, 'rb').read()

covr = []
if albumart.endswith('png'):
    covr.append(MP4Cover(data, MP4Cover.FORMAT_PNG))
else:
    covr.append(MP4Cover(data, MP4Cover.FORMAT_JPEG))

audio.tags['covr'] = covr
audio.save()   
like image 334
foosion Avatar asked Sep 01 '11 19:09

foosion


People also ask

How do you know if album artwork is embedded?

One way is to use a tag editor. Tag editors (or sometimes just 'taggers') are software that display the internal tags stored inside MP3s and other music files. Embedded album art is just another one of these tags, and so most MP3 tagging software will show any album art already embedded in your files.

Can FLAC hold album art?

Depending on what music player you are using, you can usually manually add album artwork pretty-easily. I generally use a 600 x 600 jpeg as the display file. The player might not display it at that size but it can usually downsize it if it needs too.

Can MP3 files contain images?

A standard MP3 file only contains audio data, with no additional information about the artist or type of audio contained within it. To include such extra information in an MP3 track, tag data is usually added to the beginning or end of the audio file in ID3 format.


1 Answers

Embed flac:

from mutagen import File
from mutagen.flac import Picture, FLAC

def add_flac_cover(filename, albumart):
    audio = File(filename)
        
    image = Picture()
    image.type = 3
    if albumart.endswith('png'):
        mime = 'image/png'
    else:
        mime = 'image/jpeg'
    image.desc = 'front cover'
    with open(albumart, 'rb') as f: # better than open(albumart, 'rb').read() ?
        image.data = f.read()
    
    audio.add_picture(image)
    audio.save()

For completeness, detect picture

def pict_test(audio):
    try: 
        x = audio.pictures
        if x:
            return True
    except Exception:
        pass  
    if 'covr' in audio or 'APIC:' in audio:
        return True
    return False
like image 134
foosion Avatar answered Sep 20 '22 06:09

foosion