def add_albumart(albumart, song_title): try: img = urlopen(albumart) # Gets album art from url except Exception: #log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read() # Reads and adds album art )) audio.save()
def mp3Picture(img_path, *args, **kwargs): ''' Creates a mutagen APIC object, sets its mimetype, its type and its description. Then loads the selected img and returns the Picture object. ''' # Set the corresponding mime type if img_path.endswith('png'): mime_type = 'image/png' else: mime_type = 'image/jpg' # Open bytes like object for the image albumart = open(img_path, 'rb').read() # Create Image object for mp3s and set its properties apic = APIC( encoding=3, mime=mime_type, type=3, desc='front cover', data=albumart ) return apic
def _add_cover_image(cover_image: 'Image', podcast_file: Path): if podcast_file.exists() and cover_image: metadata = mutagen.File(str(podcast_file), easy=False) if type(metadata) == MP3 and not metadata.tags.getall('APIC'): logging.info(F"Adding image tag") metadata.tags.add( APIC(data=cover_image.data, mime=cover_image.type, encoding=Encoding.UTF8, type=PictureType.COVER_FRONT)) metadata.save() elif type(metadata) == MP4 and not metadata.tags.get('covr'): logging.info(F"Adding image tag to MP4") imageformat = MP4Cover.FORMAT_PNG if mimetypes.guess_extension( cover_image.type) == '.png' else MP4Cover.FORMAT_JPEG metadata['covr'] = [ MP4Cover(cover_image.data, imageformat=imageformat) ] metadata.save() elif type(metadata) not in [MP3, MP4]: raise TypeError( F"Unkown type {type(metadata)} tagging {str(self)}") else: logging.info(F"{podcast_file} already has an image")
def setID3(self, lrc, info, path): tags = ID3(path) # remove old unsychronized lyrics if len(tags.getall("USLT")) != 0: tags.delall("USLT") if ('album' in info): tags.add(TALB(encoding=3, lang='', desc='', text=info['album'][0])) if ('title' in info): tags.add(TIT2(encoding=3, lang='', desc='', text=info['title'][0])) if ('artist' in info): tags.add(TPE1(encoding=3, lang='', desc='', text=info['artist'][0])) if ('cover' in info): tags.add( APIC(encoding=3, mime='image/png', type=3, desc='cover', data=requests.get(info['cover'][0], stream=True, headers=headers).raw.read())) tags.add(USLT(encoding=3, lang='eng', desc='aaa', text=lrc)) tags.save()
def cover(self) -> APIC: """Return the cover art of the album. Raises: HTTPError: if response status code is indicative of an error Returns: APIC: the album's cover """ response = requests.get(self.images[0].url) if response.status_code != HTTPStatus.OK.value: raise HTTPError( "Failed to fetch %s" % (self.images[0].url, ), response=response, ) return APIC( encoding=3, mime="image/jpeg", type=3, desc="Cover", data=response.content, )
def set_cover(self, force=False, resize=False): """ Attach album cover image to MP3 file. :param force: When :data:`True`, encoding will be done, even if destination file exists. :type force: boolean :param resize: When :data:`True`, cover art will be resized to predefined size. :type resize: boolean """ if self.cover and (force or util.newer(self.cover, self.dst)): tmp_cover = self._cover_thumbnail(resize) imagedata = open(tmp_cover.name, 'rb').read() pic = APIC(encoding=3, mime="image/jpeg", type=3, desc=u"Front Cover", data=imagedata) audio = MP3(self.dst) audio.tags.add(pic) err = audio.save() return self._check_err(err, "MP3 add-cover failed:")
def album_art_all_songs(self, album: AnyStr, album_artist: AnyStr) -> None: """ Apply album art to all songs of the same album and artist :param album: the album name which album art has to be changed :type album: str :param album_artist: the album artist name which album art has to be changed :type album_artist: str """ for file_name in glob(f"{os.path.dirname(self.file_path)}/*.mp3"): music_file = EasyID3(file_name) if music_file['album'][0] == album and music_file['albumartist'][ 0] == album_artist: with self.saving(MP3(file_name)) as mp3_file: with open(self.image_cover_art.source, 'rb') as alb_art: mp3_file.tags.add( APIC( mime= f'image/{pathlib.Path(self.image_cover_art.source).suffix}', type=3, desc=u'Cover', data=alb_art.read(), encoding=1))
def saveTag(link, AlbumInfo, file, lyrics): print(link) print(AlbumInfo) fd = urllib.request.urlopen(link) audio = EasyID3(file) audio['title'] = AlbumInfo[0] audio['artist'] = AlbumInfo[1] audio['album'] = AlbumInfo[2] audio['date'] = AlbumInfo[3][:4] audio['genre'] = AlbumInfo[4] audio.save() audio = MP3(file, ID3=ID3) audio.tags.add( APIC(encoding=3, mime='image/jpg', type=3, desc=u'Cover', data=fd.read())) audio.save() audio = ID3(file) audio['USLT'] = (USLT(encoding=3, text=lyrics)) audio.save() if AlbumInfo[0].find("(") != -1 and AlbumInfo[0].find(")") != -1: print(AlbumInfo[0][:AlbumInfo[0].find("(")]) print(AlbumInfo[0][AlbumInfo[0].rfind(")") + 1:]) AlbumInfo[0]=AlbumInfo[0][:AlbumInfo[0].find("(")]\ +AlbumInfo[0][AlbumInfo[0].rfind(")")+1:] if AlbumInfo[1].find("(") != -1 and AlbumInfo[1].find(")") != -1: AlbumInfo[1]=AlbumInfo[1][:AlbumInfo[1].find("(")]\ +AlbumInfo[1][AlbumInfo[1].rfind(")")+1:] fileRoute = "Music/" + AlbumInfo[0].strip() + "-" + AlbumInfo[1].strip( ) + ".mp3" fileRoute = fileRoute.replace("?", "#") if not os.path.isfile(fileRoute): os.rename(file, fileRoute)
def id3_tag(path, station, station_alias, recording_time): podcast_img = PODCAST_IMG_PATH + station_alias + '.jpg' if os.path.isfile(podcast_img) is False: podcast_img = PODCAST_IMG_PATH + 'default.jpg' audio = ID3() audio.save(path) audio = ID3(path) audio.add( TIT2(encoding=3, text='{0}, {1:%d.%m.%Y, %H:%M} Uhr'.format( station, recording_time))) audio.add(TPE1(encoding=3, text=station)) audio.add(TALB(encoding=3, text='{0:%Y-%m-%d}'.format(recording_time))) audio.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=open(podcast_img).read())) audio.save(v2_version=3)
def write_tags(song, data): try: tag = FLAC(song) tag.delete() images = Picture() images.type = 3 images.data = data['image'] tag.add_picture(images) tag['lyrics'] = data['lyric'] except mutagen.flac.FLACNoHeaderError: tag = mutagen.File(song, easy=True) tag['artist'] = data['artist'] tag['title'] = data['music'] tag['date'] = data['year'] tag['album'] = data['album'] tag['tracknumber'] = data['tracknum'] tag['discnumber'] = data['discnum'] tag['genre'] = data['genre'] tag['albumartist'] = data['ar_album'] tag['author'] = data['author'] tag['composer'] = data['composer'] tag['copyright'] = data['copyright'] tag['bpm'] = data['bpm'] tag['length'] = data['duration'] tag['organization'] = data['label'] tag['isrc'] = data['isrc'] tag['replaygain_*_gain'] = data['gain'] tag['lyricist'] = data['lyricist'] tag.save() try: audio = ID3(song) audio['APIC'] = APIC(encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=data['image']) audio['USLT'] = USLT(encoding=3, lang=u'eng', desc=u'desc', text=data['lyric']) audio.save() except mutagen.id3._util.ID3NoHeaderError: pass
def UpdateCoverMp3(lossyFileName, artworkFileName): from mutagen.id3 import ID3, APIC import tempfile from shutil import copyfile # Use copyfile b/c this will *not* copy rights (which is error prone on gvfs/samba) Log('- embedding album art in ' + lossyFileName) # Copy lossy file to a local location; to prevent (save) errors in a samba environment tempLossyFile = tempfile.gettempdir() + '/' + 'temp.mp3' copyfile(lossyFileName, tempLossyFile) audio = ID3(tempLossyFile) with open(artworkFileName, 'rb') as albumart: audio['APIC'] = APIC( encoding=3, mime='image/jpeg', type=3, desc=u'cover', data=albumart.read()) audio.save() copyfile(tempLossyFile, lossyFileName) os.remove(tempLossyFile) return
def add_metadata_to_song(file_path, cover_path): # If no ID3 tags in mp3 file try: audio = MP3(file_path, ID3=ID3) except HeaderNotFoundError: print('Can\'t sync to MPEG frame, not an validate MP3 file!') return if audio.tags is None: print('No ID3 tag, trying to add one!') try: audio.add_tags() audio.save() except error as e: print('Error occur when add tags:', str(e)) return # Modify ID3 tags id3 = ID3(file_path) # Remove old 'APIC' frame # Because two 'APIC' may exist together with the different description # For more information visit: # http://mutagen.readthedocs.io/en/latest/user/id3.html if id3.getall('APIC'): id3.delall('APIC') # add album cover id3.add( APIC( # 3 is for UTF8, but here we use 0 (LATIN1) for 163, orz~~~ encoding=0, mime='image/jpeg', # image/jpeg or image/png type=3, # 3 is for the cover(front) image data=open(cover_path, 'rb').read() ) ) id3.save(v2_version=3)
def Save(self, item, filepath): response = requests.get(item.ImageUrl) img = PIL.Image.open(BytesIO(response.content)) img.save("Temp.jpg") audio = mutagen.File(filepath) try: audio.add_tags(ID3=ID3) except mutagen.id3.error: print("has tags") audio.clear() audio.tags.add( APIC(3, 'image/jpeg', 3, u'Front Cover', open('Temp.jpg', 'rb').read())) audio.save() song = taglib.File(filepath) pprint.pprint(song.tags) song.tags['ALBUM'] = [item.AlbumName] song.tags['ALBUMARTIST'] = [item.Artists[0]] song.tags['ARTIST'] = item.Artists song.tags['DATE'] = [str(item.Year)] song.tags['GENRE'] = item.Genres song.tags['TITLE'] = [item.TrackName] song.tags['TRACKNUMBER'] = [str(item.TrackNumber)] song.save() song.close() f = open(filepath, 'rb') f.flush() f.close() print("Done.")
def mp4to3(filename, thumbnailName): root, ext = os.path.splitext(filename) if ext not in ['.m4a', '.mp4']: return newname = '%s.mp3' % root # video to mp3 cmd = 'ffmpeg -i "%s" -ab 256k "%s"' % (filename, newname) os.system(cmd) os.remove(filename) # サムネイル画像をmp3ファイルに埋め込む f = eyed3.load(newname) print(f) print(f.tag) if f.tag is None: f.initTag() with open(thumbnailName, 'rb') as dest_png: f.tag.images.set(ImageFrame.FRONT_COVER, dest_png.read(), 'image/jpeg') f.tag.save(encoding='utf-8') print(newname) audio = MP3(newname, ID3=ID3) # ジャケット画像 audio['TALB'] = TALB(encoding=3, text="うま娘") audio['APIC'] = APIC( encoding=0, # 3 is for utf-8 mime='image/jpeg', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=open(thumbnailName, encoding='ISO-8859-1').read().encode()) audio.save(v2_version=3) os.remove(thumbnailName) # ファイル移動 shutil.move('./' + newname, '../assets/mp3/')
def add_meta(self): #test artist and album tags with mutagen if self.artist != EMPTY: for file in listdir(self.folder): file_path = self.folder + "/" + file audiofile = eyed3.load(file_path) audiofile.tag.artist = self.artist_text audiofile.tag.save() if self.album != EMPTY: for file in listdir(self.folder): file_path = self.folder + "/" + file audiofile = eyed3.load(file_path) audiofile.tag.album = self.album_text audiofile.tag.save() if self.art != None: for file in listdir(self.folder): file_path = self.folder + "/" + file audiofile = MP3(file_path, ID3=ID3) audiofile.tags.add( APIC(mime='image/jpeg', type=3, desc=u'Cover', data=open(self.art, 'rb').read())) audiofile.save()
def _add_logo(self, show, audio): # APIC part taken from http://mamu.backmeister.name/praxis-tipps/pythonmutagen-audiodateien-mit-bildern-versehen/ url = show.station.logo_url if url is not None: request = Request(url) request.get_method = lambda: 'HEAD' try: response = urlopen(request) logo_type = response.info().gettype() if logo_type in ['image/jpeg', 'image/png']: img_data = urlopen(url).read() img = APIC( encoding=3, # 3 is for utf-8 mime=logo_type, type=3, # 3 is for the cover image desc=u'Station logo', data=img_data) audio.add(img) except (HTTPError, URLError) as e: message = "Error during capturing %s - %s" % (url, e) self.log.error(message) except Exception as e: raise e
def as_mp3(self): """ Embed metadata to MP3 files. """ music_file = self.music_file meta_tags = self.meta_tags # EasyID3 is fun to use ;) # For supported easyid3 tags: # https://github.com/quodlibet/mutagen/blob/master/mutagen/easyid3.py # Check out somewhere at end of above linked file audiofile = EasyID3(music_file) audiofile['artist'] = meta_tags['artists'][0]['name'] audiofile['albumartist'] = meta_tags['artists'][0]['name'] audiofile['album'] = meta_tags['album']['name'] audiofile['title'] = meta_tags['name'] audiofile['tracknumber'] = [ meta_tags['track_number'], meta_tags['total_tracks'] ] audiofile['discnumber'] = [meta_tags['disc_number'], 0] audiofile['date'] = meta_tags['release_date'] audiofile['originaldate'] = meta_tags['release_date'] audiofile['media'] = meta_tags['type'] audiofile['author'] = meta_tags['artists'][0]['name'] audiofile['lyricist'] = meta_tags['artists'][0]['name'] audiofile['arranger'] = meta_tags['artists'][0]['name'] audiofile['performer'] = meta_tags['artists'][0]['name'] audiofile['website'] = meta_tags['external_urls']['spotify'] audiofile['length'] = str(meta_tags['duration']) if meta_tags['publisher']: audiofile['encodedby'] = meta_tags['publisher'] if meta_tags['genre']: audiofile['genre'] = meta_tags['genre'] if meta_tags['copyright']: audiofile['copyright'] = meta_tags['copyright'] if meta_tags['external_ids']['isrc']: audiofile['isrc'] = meta_tags['external_ids']['isrc'] audiofile.save(v2_version=3) # For supported id3 tags: # https://github.com/quodlibet/mutagen/blob/master/mutagen/id3/_frames.py # Each class represents an id3 tag audiofile = ID3(music_file) audiofile['TORY'] = TORY(encoding=3, text=meta_tags['year']) audiofile['TYER'] = TYER(encoding=3, text=meta_tags['year']) audiofile['TPUB'] = TPUB(encoding=3, text=meta_tags['publisher']) audiofile['COMM'] = COMM(encoding=3, text=meta_tags['external_urls']['spotify']) if meta_tags['lyrics']: audiofile['USLT'] = USLT(encoding=3, desc=u'Lyrics', text=meta_tags['lyrics']) try: albumart = urllib.request.urlopen( meta_tags['album']['images'][0]['url']) audiofile['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=albumart.read()) albumart.close() except IndexError: pass audiofile.save(v2_version=3) return True
def setData(SONG_INFO, is_quiet): """Add the metadata to the song.""" # A variable to see if cover image was added. IS_IMG_ADDED = False try: # If more than one choice then call getChoice if len(SONG_INFO) > 1 and not is_quiet: option = getChoice(SONG_INFO, 'metadata') else: option = 0 SONG_PATH = os.path.join(defaults.DEFAULT.SONG_TEMP_DIR, 'ytmdl_temp.mp3_new.mp3') audio = MP3(SONG_PATH, ID3=ID3) data = ID3(SONG_PATH) # Download the cover image, if failed, pass if dwCover(SONG_INFO, option): imagedata = open(defaults.DEFAULT.COVER_IMG, 'rb').read() data.add(APIC(3, 'image/jpeg', 3, 'Front cover', imagedata)) # REmove the image os.remove(defaults.DEFAULT.COVER_IMG) IS_IMG_ADDED = True # If tags are not present then add them try: audio.add_tags() except Exception: pass audio.save() option = int(option) data.add(TYER(encoding=3, text=SONG_INFO[option].release_date)) data.add(TIT2(encoding=3, text=SONG_INFO[option].track_name)) data.add(TPE1(encoding=3, text=SONG_INFO[option].artist_name)) data.add(TALB(encoding=3, text=SONG_INFO[option].collection_name)) data.add(TCON(encoding=3, text=SONG_INFO[option].primary_genre_name)) data.add(TRCK(encoding=3, text=str(SONG_INFO[option].track_number))) data.save() defaults.DEFAULT.SONG_NAME_TO_SAVE = SONG_INFO[ option].track_name + '.mp3' # Rename the downloaded file os.rename( SONG_PATH, os.path.join(defaults.DEFAULT.SONG_TEMP_DIR, defaults.DEFAULT.SONG_NAME_TO_SAVE)) # Show the written stuff in a better format prepend.PREPEND(1) print('================================') print(' || YEAR: ' + SONG_INFO[option].release_date) print(' || TITLE: ' + SONG_INFO[option].track_name) print(' || ARITST: ' + SONG_INFO[option].artist_name) print(' || ALBUM: ' + SONG_INFO[option].collection_name) print(' || GENRE: ' + SONG_INFO[option].primary_genre_name) print(' || TRACK NO: ' + str(SONG_INFO[option].track_number)) if IS_IMG_ADDED: print(' || ALBUM COVER ADDED') prepend.PREPEND(1) print('================================') return option except Exception: return False
def generate_metadata(path, title, artist): """Fetch a song's metadata from Spotify.""" # token is required to grab metadata token = generate_token() spotify = spotipy.Spotify(auth=token) try: meta_tags = spotify.search(title + ' ' + artist, limit=1)['tracks']['items'][0] except: return False artist = spotify.artist(meta_tags['artists'][0]['id']) album = spotify.album(meta_tags['album']['id']) try: meta_tags[u'genre'] = titlecase(artist['genres'][0]) except IndexError: meta_tags[u'genre'] = None try: meta_tags[u'copyright'] = album['copyrights'][0]['text'] except IndexError: meta_tags[u'copyright'] = None try: meta_tags['isrc'] except KeyError: meta_tags['isrc'] = None meta_tags[u'release_date'] = album['release_date'] meta_tags[u'publisher'] = album['label'] meta_tags[u'total_tracks'] = album['tracks']['total'] if meta_tags is None: print('Could not find metadata...') return False """Embed metadata to MP3 files.""" audiofile = EasyID3(path) audiofile['artist'] = meta_tags['artists'][0]['name'] audiofile['albumartist'] = meta_tags['artists'][0]['name'] audiofile['album'] = meta_tags['album']['name'] audiofile['title'] = meta_tags['name'] audiofile['tracknumber'] = [meta_tags['track_number'], meta_tags['total_tracks']] audiofile['discnumber'] = [meta_tags['disc_number'], 0] audiofile['date'] = meta_tags['release_date'] audiofile['originaldate'] = meta_tags['release_date'] audiofile['media'] = meta_tags['type'] audiofile['author'] = meta_tags['artists'][0]['name'] audiofile['lyricist'] = meta_tags['artists'][0]['name'] audiofile['arranger'] = meta_tags['artists'][0]['name'] audiofile['performer'] = meta_tags['artists'][0]['name'] audiofile['encodedby'] = meta_tags['publisher'] audiofile['website'] = meta_tags['external_urls']['spotify'] audiofile['length'] = str(meta_tags['duration_ms'] / 1000) if meta_tags['genre']: audiofile['genre'] = meta_tags['genre'] if meta_tags['copyright']: audiofile['copyright'] = meta_tags['copyright'] if meta_tags['isrc']: audiofile['isrc'] = meta_tags['external_ids']['isrc'] audiofile.save(v2_version=3) audiofile = ID3(path) try: albumart = urllib.request.urlopen(meta_tags['album']['images'][0]['url']) audiofile["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=albumart.read()) albumart.close() except IndexError: pass audiofile.save(v2_version=3) print('Fixed metadata...') return True
def main(): parser = argparse.ArgumentParser( 'Change or manipulate the ID3 tags of the audio files') parser.add_argument('--track', '-n', type=int, default=None, help='set the track number') parser.add_argument('--track-total', '-N', type=int, default=None, help='set total number of tracks') parser.add_argument('--artist', '-a', default=None, help='set the artist name') parser.add_argument('--album', '-A', default=None, help='set the album name') parser.add_argument('--title', '-t', default=None, help='set the title name') parser.add_argument('--wors', '-r', default=None, help='set the internet radio url') parser.add_argument('--year', '-Y', default=None, help='set the release year') parser.add_argument('--cover', '-c', default=None, help='set the cover image') parser.add_argument('--format', '-f', default=None, help='return the ID3 information as a formatted' '''string; the format string should containing one or more''' ''' of the following specifiers: , {track} , {artist} , {title} , {album} , {year} , {kbps} , {wors} , {len} (the length of the audio file, in seconds) , {path} (the absolute path of the file)''') parser.add_argument('--separator', '-s', default='\n', help='define the separator used to append at the end' ' of the output for each file (excluding the last' ' file)') parser.add_argument('--escape', '-e', default='', help='define the characters that should be escaped in' ' all the outputed fields') parser.add_argument('audiofile', nargs='+', help='an audio file containing the ID3 tags') args = parser.parse_args() # input section to_track = args.track to_track_total = args.track_total to_artist = args.artist to_album = args.album to_title = args.title to_wors = args.wors to_year = args.year to_cover = args.cover if to_cover is not None: cover_ext = os.path.splitext(to_cover)[1] # print("Cover path is "+to_cover) import mimetypes mimetypes.init() to_cover_mime = mimetypes.types_map[cover_ext] # print("Mime type is "+to_cover_mime) # output section outputs = [] formatstr = args.format escapepat = "" delimiter = '' for c in args.escape: esc = '' if c in r'()[]\^$.|?*+{}': esc = '\\' escapepat = escapepat + delimiter + esc + c delimiter = '|' to_escape = False if escapepat != '': to_escape = True escapepat = '(%s)' % escapepat separator = args.separator def getinfo(file_): try: return (file_.info.bitrate / 1000, int(round(file_.info.length))) except: return (0, 0) for f in args.audiofile: path = os.path.realpath(f) artist = title = album = year = wors = "" file_ = File(f) kbps, len_ = getinfo(file_) try: if (type(file_) == MP3): # add ID3 tag if it doesn't exist try: file_.add_tags() except: pass # should we set the tag in anyway? if to_track is not None or to_track_total is not None: old = (0, 0) if 'TRCK' in file_: try: old = tuple( map(int, file_['TRCK'].text[0].split('/'))) old = (old + (0, 0))[:2] except: pass if to_track is None: to_track = old[0] if to_track_total is None: to_track_total = old[1] file_['TRCK'] = TRCK( encoding=3, text='%02d' % to_track + ' / %02d' % to_track_total if to_track_total else '') if to_track == 0 and to_track_total == 0: del file_['TRCK'] if to_artist is not None: file_['TPE1'] = TPE1(encoding=3, text=to_artist) if to_album is not None: file_['TALB'] = TALB(encoding=3, text=to_album) if to_title is not None: file_['TIT2'] = TIT2(encoding=3, text=to_title) if to_wors is not None: file_['WORS'] = WORS(url=to_wors) if to_year is not None: file_['TDRL'] = TDRL(encoding=3, text=to_year) if to_cover is not None: # print('The image data is '+open(to_cover).read()) file_['APIC:'] = APIC(encoding=3, mime=to_cover_mime, type=3, data=open(to_cover).read()) file_.save() # process mp3 specific tag information track = file_['TRCK'].text[0] if 'TRCK' in file_ \ else '' artist = file_['TPE1'].text[0] if 'TPE1' in file_ \ else '' album = file_['TALB'].text[0] if 'TALB' in file_ \ else '' title = file_['TIT2'].text[0] if 'TIT2' in file_ \ else '' wors = file_['WORS'].url if 'WORS' in file_ else '' year = file_['TDRL'].text[0] if 'TDRL' in file_ else '' elif (type(file_) == MP4): # should we set the tag in anyway? if to_track is not None or to_track_total is not None: old = (0, 0) if 'trkn' in file_: try: old = tuple(map(int, file_['trkn'][0])) old = (old + (0, 0))[:2] except: pass if to_track is None: to_track = old[0] if to_track_total is None: to_track_total = old[1] file_['trkn'] = [(to_track, to_track_total)] if to_track == 0 and to_track_total == 0: del file_['trkn'] if to_artist is not None: file_['\xa9ART'] = [to_artist] if to_album is not None: file_['\xa9alb'] = [to_album] if to_title is not None: file_['\xa9nam'] = [to_title] if to_year is not None: file_['\xa9day'] = [to_year] if to_cover is not None: file_['covr'] = [open(to_cover).read()] file_.save() track = '%02d / %02d' % file_['trkn'][0] if 'trkn' in file_ \ else '' artist = file_['\xa9ART'][0] if '\xa9ART' in file_ \ else '' album = file_['\xa9alb'][0] if '\xa9alb' in file_ \ else '' title = file_['\xa9nam'][0] if '\xa9nam' in file_ \ else '' year = file_['\xa9day'][0] if '\xa9day' in file_ \ else '' except: pass reps = { 'track': track, 'artist': artist, 'title': title, 'album': album, 'year': year, "kbps": kbps, 'wors': wors, 'len': len_, 'path': path } if to_escape: for k in reps: reps[k] = re.sub(escapepat, r'\\\1', u"%s" % reps[k]) if formatstr is not None: outputs.append(formatstr.format(**reps)) output = separator.join(outputs) print(output, end='')
from mutagen.easyid3 import EasyID3 from mutagen.mp3 import MP3 from mutagen.id3 import ID3, APIC, error # address = "F:\mygithub\change_mp3\data/first.mp3" # address = "F:\mygithub\change_mp3\data/pick_bila_waktu_telah_berakhir.mp3" # address = "F:\mygithub\change_mp3\data/pick_taubat.mp3" address = "F:\mygithub\change_mp3\data/sholawat_nabi_maulidu_ahmad.mp3" audio = MP3(address, ID3=ID3) try: audio.add_tags() except error: pass audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime='image/jpg', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=open('F:\mygithub\change_mp3\icon\icon_1.jpg', "rb").read())) audio.save() audio = EasyID3(address) audio['artist'] = "artist" audio['title'] = "title" audio['tracknumber'] = "tracknumber" audio['album'] = "album" audio.save()
if not tags: print('no tags') os.remove(filepath_pic) exit() # if if 'APIC' in tags: print('picture already exists') os.remove(filepath_pic) exit() # if img_data = open(filepath_img, 'rb').read() tags.add( APIC( encoding=3, # 3 is for utf-8 mime=img_mime, # image/jpeg or image/png type=3, # 3 is for the cover image desc='Cover', data=img_data ) ) #tags.save(filepath_pic) tags.save(v2_version=3) print('saved: ', filepath_pic)
def addImage(self, desc, type, data, format): self.id3file.add(APIC(3, 'image/' + str(format), type, desc, data)) self.id3file.save()
if hasattr(cmd_options, arg): value_to_assign = getattr(cmd_options, arg) if tag in existing_tags: current_value = existing_tags[tag] if value_to_assign: new_tags[tag] = ctr(encoding=3, text=[value_to_assign]) elif current_value: new_tags[tag] = current_value if cmd_options.cover: if cmd_options.cover.upper().endswith( "JPG") or cmd_options.cover.upper().endswith("JPEG"): with open(cmd_options.cover, "rb") as fd: new_tags["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Front Cover', data=fd.read()) elif cmd_options.coverlink: print("Downloading cover") cmd = ["curl", cmd_options.coverlink, "-o", "cover.jpg"] cmd_str = " ".join(cmd) print("Executing:%s" % cmd_str) subprocess.check_output(cmd) with open("cover.jpg", "rb") as fd: new_tags["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc='Front Cover', data=fd.read()) elif u"APIC:" in existing_tags:
def set_MP3_data(SONG_INFO, is_quiet, song_path, choice): """ Set the meta data if the passed data is mp3. """ # A variable to see if cover image was added. IS_IMG_ADDED = False try: # If more than one choice then call getChoice option = 0 if len(SONG_INFO) > 1: if not is_quiet: option = getChoice(SONG_INFO, 'metadata') elif choice is not None and choice in range(1, len(SONG_INFO)): option = choice SONG_PATH = os.path.join(defaults.DEFAULT.SONG_TEMP_DIR, song_path) audio = MP3(SONG_PATH, ID3=ID3) data = ID3(SONG_PATH) # Download the cover image, if failed, pass if dwCover(SONG_INFO, option): imagedata = open(defaults.DEFAULT.COVER_IMG, 'rb').read() data.add(APIC(3, 'image/jpeg', 3, 'Front cover', imagedata)) # REmove the image os.remove(defaults.DEFAULT.COVER_IMG) IS_IMG_ADDED = True # If tags are not present then add them try: audio.add_tags() except Exception: pass audio.save() option = int(option) data.add(TYER(encoding=3, text=SONG_INFO[option].release_date)) data.add(TIT2(encoding=3, text=SONG_INFO[option].track_name)) data.add(TPE1(encoding=3, text=SONG_INFO[option].artist_name)) data.add(TALB(encoding=3, text=SONG_INFO[option].collection_name)) data.add(TCON(encoding=3, text=SONG_INFO[option].primary_genre_name)) data.add(TRCK(encoding=3, text=str(SONG_INFO[option].track_number))) data.save() defaults.DEFAULT.SONG_NAME_TO_SAVE = SONG_INFO[ option].track_name + '.mp3' # Rename the downloaded file os.rename( SONG_PATH, os.path.join(defaults.DEFAULT.SONG_TEMP_DIR, defaults.DEFAULT.SONG_NAME_TO_SAVE)) return option, IS_IMG_ADDED except Exception as e: logger.debug("{}".format(e)) return e, False
def retrieve_covers(songlist, usealbum=False, fillalbum=False): getter = CoverGetter() covers = {} albums = {} songs = {} threads = [] for song in songlist: try: print "Looking for cover for ", song meta = ID3(song) artist = str(meta["TPE1"]) artist = re.sub('Featuring.*$', '', artist) artist = re.sub('featuring.*$', '', artist) artist = re.sub('Ft\..*$', '', artist) artist = re.sub('ft\..*$', '', artist) artist = artist.strip() track = str(meta["TIT2"]) track = re.sub('\(.*?\)', '', track) album = None if usealbum: try: album = str(meta["TALB"]) except: pass if album == None: album = getter.get_album(artist, track) album = album.encode("iso-8859-1", "ignore") cover_id = artist + " " + album songs[song] = cover_id if cover_id not in covers: try: albums[cover_id] = unicode(album) except: try: albums[cover_id] = album.decode('latin-1') except: albums[cover_id] = album.decode('utf-8') covers[cover_id] = None cover_urls = getter.get_cover_urls(artist, album) if len(cover_urls) > 0: print "Fetching cover for ", cover_id thread = FetchThread(cover_id, cover_urls) thread.start() threads.append(thread) else: print "Error no cover found for ", cover_id except: print "Unexpected error processing", song traceback.print_exc() print "Waiting to fetch all covers." for thread in threads: thread.join() covers[thread.coverid] = thread.cover print "Writing all covers" for song in songs.keys(): cover_id = songs[song] cover = covers[cover_id] try: if cover != None: print "Writing cover for ", song meta = ID3(song) if fillalbum: meta["TALB"] = TALB(encoding=3, text=albums[cover_id]) meta.delall('APIC') meta.add( APIC(encoding=3, mime="image/%s" % cover[0], type=3, desc=u'Front Cover', data=cover[1])) meta.save() except: print "Error writing cover for ", song traceback.print_exc()
# print(direc, directory) if len(directory) == 0: continue pic_file = direc + '/folder.jpg' if not os.path.exists(pic_file): continue try: imagedata = open(pic_file, 'rb').read() except Exception: print(pic_file) continue for file in directory: if '.mp3' not in file: continue mp3file = direc + '/' + file audio = MP3(mp3file, ID3=ID3) try: audio.add_tags() except error: pass audio.tags.add( APIC( encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=imagedata ) ) audio.save()
def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None): """ Attempt to put ID3 tags on a file. Args: artist (str): title (str): year (int): genre (str): artwork_url (str): album (str): track_number (str): filename (str): """ try: audio = EasyMP3(filename) audio.tags = None audio["artist"] = artist audio["title"] = title if year: audio["date"] = str(str(year).encode('ascii', 'ignore')) if album: audio["album"] = album if track_number: audio["tracknumber"] = track_number if genre: audio["genre"] = genre audio.save() if artwork_url: artwork_url = artwork_url.replace('https', 'http') mime = 'image/jpeg' if '.jpg' in artwork_url: mime = 'image/jpeg' if '.png' in artwork_url: mime = 'image/png' if '-large' in artwork_url: new_artwork_url = artwork_url.replace('-large', '-t500x500') try: image_data = requests.get(new_artwork_url).content except Exception as e: # No very large image available. image_data = requests.get(artwork_url).content else: image_data = requests.get(artwork_url).content audio = MP3(filename, ID3=OldID3) audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime=mime, type=3, # 3 is for the cover image desc='Cover', data=image_data)) audio.save() return True except Exception as e: puts( colored.red("Problem tagging file: ") + colored.white("Is this file a WAV?")) return False
def picture(self, url): from mutagen.id3 import APIC self.audio.add(APIC(mime='image/jpeg', data=get(url).content))
def tagUpdateAll(filePath, tags): album = tags['album'] lyrics = tags['lyrics'] artist = tags['artist'] track = tags['track'] title = tags['title'] albumImage = tags['albumImage'] year = tags['year'] genre = tags['genre'] """ logger.debug( "album \t: " + album ) logger.debug( "lyrics \t: " + lyrics ) logger.debug( "artist \t: " + artist ) logger.debug( "track \t: " + track ) logger.debug( "title \t: " + title ) logger.debug( "albumImage \t: " + albumImage ) logger.debug( "year \t: " + year ) logger.debug( "genre \t: " + genre ) """ if os.path.isfile(filePath): logger.debug("파일존재 확인" + filePath) ext = filePath.split(".")[-1] if ext.upper() == "MP3": try: audio = ID3(filePath) audio.add(TALB(text=[album])) audio.add(TIT2(text=[title])) audio.add(TPE1(text=[artist])) audio.add(TRCK(text=[track])) audio.add(TYER(text=[year])) audio.add(TCON(text=[genre])) audio.add(USLT(text=lyrics, lang="kor", desc="")) from PIL import Image import requests coverFile = os.path.join(path_app_root, 'data', 'tmp', 'cover.jpg') if os.path.isfile(coverFile): os.remove(coverFile) logger.debug("albumImage : %s " , albumImage) res = requests.get(albumImage, stream=True) if "png".upper() in res.headers['Content-Type'].upper(): im = Image.open(res.raw) bg = Image.new("RGB", im.size, (255,255,255)) bg.paste(im,im) bg.save(coverFile) else: im = Image.open(res.raw) im.save(coverFile) audio.add(APIC(encoding=3, mime=res.headers['Content-Type'], type=3, desc=u'Cover', data=open(coverFile, 'rb').read())) audio.save() except ID3NoHeaderError: logger.debug("MP3 except") audio = ID3() audio.add(TALB(text=[album])) audio.add(TIT2(text=[title])) audio.add(TPE1(text=[artist])) audio.add(TRCK(text=[track])) audio.add(TYER(text=[year])) audio.add(TCON(text=[genre])) audio.add(USLT(text=[lyrics], lang="kor", desc="")) from PIL import Image import requests coverFile = os.path.join(path_app_root, 'data', 'tmp', 'cover.jpg') im = Image.open(requests.get(albumImage, stream=True).raw) if os.path.isfile(coverFile): os.remove(coverFile) im.save(coverFile) audio.add(APIC(encoding=3, mime='image/jpg', type=3, desc=u'Cover', data=open(coverFile, 'rb').read())) audio.save(filePath)