def set_MP3_data(song, option, song_path): """ Set the meta data if the passed data is mp3. """ # A variable to see if cover image was added. IS_IMG_ADDED = False try: 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): 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() data.add(TYER(encoding=3, text=song.release_date)) data.add(TIT2(encoding=3, text=song.track_name)) data.add(TPE1(encoding=3, text=song.artist_name)) data.add(TALB(encoding=3, text=song.collection_name)) data.add(TCON(encoding=3, text=song.primary_genre_name)) data.add(TRCK(encoding=3, text=str(song.track_number))) data.save() defaults.DEFAULT.SONG_NAME_TO_SAVE = song.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 IS_IMG_ADDED except Exception as e: logger.debug("{}".format(e)) return e, False
def modified_id3(self, file_name, info): id3 = ID3() id3.add(TRCK(encoding=3, text=info['track'])) id3.add(TIT2(encoding=3, text=info['song_name'])) id3.add(TALB(encoding=3, text=info['album_name'])) id3.add(TPE1(encoding=3, text=info['artist_name'])) id3.add(COMM(encoding=3, desc=u'Comment', text=info['song_url'])) id3.add( APIC(encoding=3, mime=u'image/jpg', type=3, desc=u'Cover', data=self.get_cover(info['album_pic_url']))) id3.save(file_name)
def save(self, *, file_path=None, title=None, album=None, artist=None, sync_lrc=None, unsync_lrc=None, img=None, url=None): """保存歌曲的ID3信息""" if img: self.tag.setall( 'APIC', [ APIC( encoding=Encoding. LATIN1, # if other apple music/itunes can't display img mime='image/jpeg', # image/jpeg or image/png type=PictureType. COVER_FRONT, # 3 is for the cover image data=img) ]) if sync_lrc: # Sample: format=2, type=1, text=[("Do you know what's worth fighting for'", 17640), ...]) # 不知道 format=2, type=1 的含义,这是使用ID3读取现有mp3逆向得到的 self.tag.setall("SYLT", [ SYLT(encoding=Encoding.UTF8, lang='eng', format=2, type=1, text=sync_lrc) ]) if unsync_lrc: self.tag.setall( "USLT", [USLT(encoding=Encoding.UTF8, lang='eng', text=unsync_lrc)]) if title: self.tag.setall("TIT2", [TIT2(encoding=Encoding.UTF8, text=title)]) if album: self.tag.setall("TALB", [TALB(encoding=Encoding.UTF8, text=album)]) if artist: self.tag.setall("TPE1", [TPE1(encoding=Encoding.UTF8, text=artist)]) if url: self.tag.setall("WXXX", [WXXX(encoding=Encoding.UTF8, url=url)]) self.tag.save(file_path or self.file_path, v2_version=3)
def test_frame_order(self): f = ID3(self.filename) f["TIT2"] = TIT2(encoding=0, text="A title!") f["APIC"] = APIC(encoding=0, mime="b", type=3, desc='', data=b"a") f["TALB"] = TALB(encoding=0, text="c") f["COMM"] = COMM(encoding=0, desc="x", text="y") f.save() with open(self.filename, 'rb') as h: data = h.read() self.assert_(data.find(b"TIT2") < data.find(b"APIC")) self.assert_(data.find(b"TIT2") < data.find(b"COMM")) self.assert_(data.find(b"TALB") < data.find(b"APIC")) self.assert_(data.find(b"TALB") < data.find(b"COMM")) self.assert_(data.find(b"TIT2") < data.find(b"TALB"))
def fill_idv3(self, cd): """docstring for fill""" if self.mp3info: self.mp3info.update({ 'TPE1':TPE1(encoding =3, text = [cd['author']]), 'TIT2':TIT2(encoding =3, text = [cd['title']]), 'TALB':TALB(encoding =3, text = [u"Записи користувача "+\ cd['user'].\ get_profile().fullname()]), "COMM::'eng'":COMM(encoding=3, lang="eng", desc="", text=[u"downloaded from minus.lviv.ua"]), "COMM":COMM(encoding=3, lang="ukr", desc="", text=[u"Звантажено з minus.lviv.ua"]) }) self.mp3info.save()
def _saveMp3(self, coverPath): self._handle.tags.add(TIT2(encoding=3, text=self.title)) self._handle.tags.add(TALB(encoding=3, text=self.album)) # self._handle.tags.add(TOPE(encoding=3, text=self.albumartist)) self._handle.tags.add(TPE1(encoding=3, text=self.artist)) self._handle.tags.add(TCOP(encoding=3, text=self.copyright)) self._handle.tags.add(TRCK(encoding=3, text=str(self.tracknumber))) # self._handle.tags.add(TRCK(encoding=3, text=self.discnum)) self._handle.tags.add(TCON(encoding=3, text=self.genre)) self._handle.tags.add(TDRC(encoding=3, text=self.date)) self._handle.tags.add(TCOM(encoding=3, text=self.composer)) self._handle.tags.add(TSRC(encoding=3, text=self.isrc)) self._savePic(coverPath) self._handle.save() return True
def SetMap3Info(id3Data: ID3, infoDict: dict): for key in infoDict.keys(): if key == "APIC": id3Data[key] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'封面', data=infoDict[key]) elif key == 'TIT2': id3Data[key] = TIT2(encoding=3, text=infoDict[key]) elif key == "TPE1": id3Data[key] = TPE1(encoding=3, text=infoDict[key]) elif key == "TALB": id3Data[key] = TALB(encoding=3, text=infoDict[key]) return id3Data
def set_data(path, song): """ Sets the ID3 meta data of the MP3 file found at the end of path. Song must be a dict """ new_song = ID3(path) new_song.delete() new_song.add(TIT2(encoding=3, text=song['title'])) new_song.add(TPE1(encoding=3, text=song['artist'])) new_song.add(TALB(encoding=3, text=song['album'])) # new_song.add(TCON(encoding=3, text=song.primary_genre_name)) new_song.save() return
def fix_metadata(file_name, search_result): """ fix_metadata(file_name: str, search_result: dict) -- fix mp3 file's metadata with search result. Arguments: file_name: str -- name of the mp3 file. search_result: dict -- a search result dict extracted from raw data. """ audio = ID3(file_name) audio['TPE1'] = TPE1(encoding=3, text=search_result['artistName']) audio['TIT2'] = TIT2(encoding=3, text=search_result['trackName']) audio['TRCK'] = TRCK(encoding=3, text=str(search_result['trackNumber'])) audio['TALB'] = TALB(encoding=3, text=search_result['collectionName']) audio.save()
def addInfoToMp3(filename, songInfo): filePath = os.path.join(songInfo["audioBasePath"], filename) audio = MP3(filePath, ID3=ID3) with open(songInfo["imgPath"], "rb") as f: data = f.read() audio["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=data) audio["TIT2"] = TIT2(encoding=3, text=songInfo["name"]) audio['TPE1'] = TPE1(encoding=3, text=songInfo['artist']) audio['TALB'] = TALB(encoding=3, text=songInfo['album']) audio.save()
def set_data(path, song): """ Sets the ID3 meta data of the MP3 file found at the end of path. Song must be a track object. """ new_song = ID3(path) new_song.delete() new_song.add(TIT2(encoding=3, text=song.track_name)) new_song.add(TPE1(encoding=3, text=song.artist_name)) new_song.add(TALB(encoding=3, text=song.collection_name)) new_song.add(TCON(encoding=3, text=song.primary_genre_name)) new_song.save() return
def finalize(self): # Apply changes to files cover = open(self.fcov + f"{self.loc_album[:15]}.jpg", 'rb').read() # id3 = ID3(f'review/{self.fname}') id3 = ID3(self.fin + f"{self.fname}") id3.add(APIC(3, 'image/jpeg', 3, "", cover)) id3.add(TT2(encoding=3, text=f"{self.loc_title}")) id3.add(TPE1(encoding=3, text=f"{self.loc_artist}")) id3.add(TALB(encoding=3, text=f"{self.loc_album}")) id3.add(USLT(encoding=3, text=f"{self.loc_lyrics}")) # Save data and relocate id3.save(v2_version=3) # shutil.move(f"review/{self.fname}", f"final/{self.loc_title}.mp3") shutil.move(self.fin + f"{self.fname}", self.fout + f"{self.loc_title}.mp3")
def SetMp3Info(path, info): songFile = ID3(path) # songFile['APIC'] = APIC( # 插入封面 # encoding=3, # mime='image/jpeg', # type=3, # desc=u'Cover', # data=info['picData'] # ) songFile['TIT2'] = TIT2( # 插入歌名 encoding=3, text=info['title']) songFile['TPE1'] = TPE1( # 插入第一演奏家、歌手、等 encoding=3, text=info['artist']) songFile['TALB'] = TALB( # 插入专辑名 encoding=3, text=info['album']) songFile.save()
def add_mp3_metadata(file_path, title='Unknown', artist='Unknown', album='Unknown', index=0, year=""): """ adds tags for the mp3 file (artist, album etc.) :param file_path: the path of the mp3 file that was downloaded :type file_path: str :param title: the title of the song :type title: str :param artist: the artist of the song :type artist: str :param album: the album that the song is part of :type album: str :param index: the index of the song in the album :type index: str :param year: the year of release of the song/ album :type year: str :return: None """ try: print("replacing the file...") AudioSegment.from_file(file_path).export(file_path, format='mp3') print("writing tags on file...") print("{} {} {} {}".format(title, album, artist, index)) except FileNotFoundError as e: print("failed to convert {} to mp3 because file not found: {}".format(title, e)) return except Exception as e: print("unhandled exception in converting {} to mp3: {}".format(title, e)) return if title is 'Unknown': title = file_path.split('\\')[-1].split('.')[0] try: audio = ID3(file_path) except ID3NoHeaderError as e: audio = ID3() audio.add(TIT2(encoding=3, text=title)) audio['TIT2'] = TIT2(encoding=Encoding.UTF8, text=title) # title audio['TPE1'] = TPE1(encoding=Encoding.UTF8, text=artist) # contributing artist audio['TPE2'] = TPE2(encoding=Encoding.UTF8, text=artist) # album artist audio['TALB'] = TALB(encoding=Encoding.UTF8, text=album) # album audio['TRCK'] = TRCK(encoding=Encoding.UTF8, text=str(index)) # track number audio['TORY'] = TORY(encoding=Encoding.UTF8, text=str(year)) # Original Release Year audio['TYER'] = TYER(encoding=Encoding.UTF8, text=str(year)) # Year Of Recording audio.save(file_path)
def write_ID3v2(self): if MUTAGEN: if "MP3" in self.__audio_codec: try: tags = ID3(self.__filepath) except ID3NoHeaderError: tags = ID3() # Track number tags["TRCK"] = TRCK(encoding=3, text=unicode(self.get_tag("track_number"))) # Title tags["TIT2"] = TIT2(encoding=3, text=unicode(self.get_tag("title"))) # Artist tags["TPE1"] = TPE1(encoding=3, text=unicode(self.get_tag("artist"))) # Album tags["TALB"] = TALB(encoding=3, text=unicode(self.get_tag("album"))) # Year tags["TDRC"] = TDRC(encoding=3, text=unicode(self.get_tag("year"))) # Genre tags["TCON"] = TCON(encoding=3, text=unicode(self.get_tag("genre"))) # Comment tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=unicode(self.get_tag("comment"))) #tags["COMM"] = COMM(encoding=3, text=unicode(self.get_tag("comment"))) # Album artist tags["TPE2"] = TPE2(encoding=3, text=unicode(self.get_tag("album_artist"))) # Composer tags["TCOM"] = TCOM(encoding=3, text=unicode(self.get_tag("composer"))) # Disc number tags["TPOS"] = TPOS(encoding=3, text=unicode(self.get_tag("disc_number"))) # Cover tags["APIC"] = APIC(3, 'image/jpeg', 3, 'Front cover', self.get_tag("cover")) #tags.update_to_v24() tags.save(self.__filepath, v1=2)
def writeTag(self, podData): try: self.audiofile.clear() self.audiofile.add_tags() except: pass self.audiofile.tags.add(TIT2(encoding=3, text=podData.Header)) self.audiofile.tags.add(TPE1(encoding=3, text=podData.Title)) self.audiofile.tags.add(TALB(encoding=3, text=podData.Title)) self.audiofile.tags.add(WXXX(encoding=3, text=podData.DownloadUrl)) self.audiofile.tags.add(COMM(encoding=3, text=podData.Description)) self.date = datetime.strptime(podData.DatePosted, "%a, %d %B %Y") self.dateinput = u"" + str(self.date.year) + "-" + str( self.date.month) + "-" + str(self.date.day) self.audiofile.tags.add(TDRC(encoding=3, text=[self.dateinput])) self.audiofile.save(v1=2)
def mp3_tags(fname, artist, year, album, no, tracks, title, genre, comment): try: audio = ID3(fname) except ID3NoHeaderError: audio = ID3() audio.add(TPE1(encoding=3, text=artist.decode('utf8'))) # Artist Name audio.add(TMCL(encoding=3, text=artist.decode('utf8'))) # Performer audio.add(TCON(encoding=3, text=genre.decode('utf8'))) # Genre audio.add(TYER(encoding=3, text=year)) # Year audio.add(TALB(encoding=3, text=album.decode('utf8'))) # Album Name audio.add(TRCK(encoding=3, text=no)) # Tracknumber # audio.add(TRCK(encoding=3, text=unicode(no, 'utf8'))) # Tracknumber audio.add(TIT2(encoding=3, text=title.decode('utf8'))) # Titel # audio.add(TIT2(encoding=3, text=unicode(title, 'utf8'))) # Titel audio.add(COMM(encoding=3, text=comment.decode('utf8'))) # Comment # audio.add(COMM(encoding=3, text=unicode(comment, 'utf8'))) # Comment audio.save(fname,v2_version=3)
def select(self, entry, path=None): if 'url' not in entry: raise ValueError('Media URL must be specified.') info = self.ydl.extract_info(entry['url']) file = '%s.mp3' % info['id'] tags = ID3() filename = entry[ 'title'] if 'title' in entry and entry['title'] else 'download' filename = re.sub(r'\W*[^a-zA-Z\d\s]\W*', '_', filename) if 'title' in entry: tags.add(TIT2(encoding=3, text=entry['title'])) if 'artist' in entry: tags.add(TPE1(encoding=3, text=entry['artist'])) if 'album' in entry: tags.add(TALB(encoding=3, text=entry['album'])) if 'img' in entry and entry['img'] != '': scheme = urlparse(entry['img']).scheme img_path = entry['img'] if scheme == '': # Local path to absolute path img_path = os.path.abspath(img_path) if scheme[:4] != 'http': # Absolute path to file URI img_path = 'file:///%s' % img_path img_request = urllib.request.urlopen(img_path) img = img_request.read() img_request.close() valid_exts = ['jpeg', 'png', 'gif', 'bmp'] ext = imghdr.what(None, img) if ext not in valid_exts: raise ValueError('%s is an unsupported file extension.' % ext) else: mime = 'image/%s' % ext tags.add(APIC(encoding=3, mime=mime, type=3, data=img)) tags.save(file, v2_version=3) if path: filename = '%s/%s' % (path, filename) if not os.path.exists(path): os.makedirs(path) target_file = '%s.mp3' % filename i = 1 while os.path.exists(target_file): target_file = '%s (%d).mp3' % (filename, i) i += 1 os.rename(file, target_file) return os.path.realpath(target_file)
def addID3(song_id, cover, lyrics, genre, artists, title, album_year, album_name, album_artist, album_track): audio = ID3(f'{song_id}.mp3') audio['APIC'] = APIC(encoding = 3, mime = 'image/jpeg', type = 3, data = cover) audio['USLT'] = USLT(encoding = 3, text = lyrics) audio['TIT2'] = TIT2(encoding = 3, text = title) audio['TPE1'] = TPE1(encoding = 3, text = artists) audio['TRCK'] = TRCK(encoding = 3, text = album_track) audio['TALB'] = TALB(encoding = 3, text = album_name) audio['TCON'] = TCON(encoding = 3, text = genre) audio['TPE2'] = TPE2(encoding = 3, text = album_artist) audio['TDRC'] = TDRC(encoding = 3, text = album_year) audio.save(v2_version=3, v23_sep='; ') logger.info(f'{title} tagged')
def setSongInfo(songfilepath, songtitle, songartist, songalbum, picdata): audio = ID3(songfilepath) #img = open(songpicpath,'rb') audio.update_to_v23() #把可能存在的旧版本升级为2.3 audio['APIC'] = APIC( #插入专辑图片 encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=picdata) audio['TIT2'] = TIT2( #插入歌名 encoding=3, text=[songtitle]) audio['TPE1'] = TPE1( #插入第一演奏家、歌手、等 encoding=3, text=[songartist]) audio['TALB'] = TALB( #插入专辑名称 encoding=3, text=[songalbum]) audio.save() #记得要保存
def clean_metadata(path): filename, filetype = os.path.splitext(path) try: origfile = ID3(path) except: origfile = ID3() # Save essential metadata artist = get_tag(origfile, 'TPE1') album = get_tag(origfile, 'TALB') title = get_tag(origfile, 'TIT2') genre = get_tag(origfile, 'TCON') track_num = get_tag(origfile, 'TRCK') year = get_tag(origfile, 'TYER') date = get_tag(origfile, 'TDRC') lyrics = get_tag(origfile, 'USLT') art = get_tag(origfile, 'APIC:') # Rename dirty file dirty_filepath = filename+"-dirty.mp3" os.rename(path, dirty_filepath) # Create new file with no tags subprocess.check_output(['ffmpeg', '-hide_banner', '-i', dirty_filepath, '-map_metadata', '-1', '-c:v', 'copy', '-c:a', 'copy', path]) # Apply desired tags to new file try: cleanfile = ID3(path) except ID3NoHeaderError: cleanfile = ID3() if artist != "": cleanfile.add(TPE1(encoding=3, text=artist)) if album != "": cleanfile.add(TALB(encoding=3, text=album)) if title != "": cleanfile.add(TIT2(encoding=3, text=title)) if genre != "": cleanfile.add(TCON(encoding=3, text=genre)) if track_num != "": cleanfile.add(TRCK(encoding=3, text=track_num)) if date != "": cleanfile.add(TDRC(encoding=3, text=date)) if year != "": cleanfile.add(TYER(encoding=3, text=year)) if year != "": cleanfile.add(TORY(encoding=3, text=year)) if lyrics != "": cleanfile.add(USLT(encoding=3, text=lyrics)) if art != "": cleanfile.add(APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=art)) cleanfile.save(path, v2_version=3) # Delete old, dirty file os.remove(dirty_filepath)
def modified_id3(self, file_name, info): id3 = ID3() id3.add(TRCK(encoding=3, text=info['track'])) id3.add(TDRC(encoding=3, text=info['year'])) id3.add(TIT2(encoding=3, text=info['song_name'])) id3.add(TALB(encoding=3, text=info['album_name'])) id3.add(TPE1(encoding=3, text=info['artist_name'])) id3.add(TPOS(encoding=3, text=info['cd_serial'])) #id3.add(USLT(encoding=3, text=self.get_lyric(info['lyric_url']))) #id3.add(TCOM(encoding=3, text=info['composer'])) #id3.add(TCON(encoding=3, text=u'genres')) #id3.add(TSST(encoding=3, text=info['sub_title'])) #id3.add(TSRC(encoding=3, text=info['disc_code'])) id3.add(COMM(encoding=3, desc=u'Comment', \ text=info['song_url'])) #id3.add(APIC(encoding=3, mime=u'image/jpg', type=3, \ #desc=u'Front Cover', data=self.get_cover(info))) id3.save(file_name)
def select(entry, path=None): '''Select the metadata to be added to the MP3.''' if 'title' in entry and entry['title']: file = download(entry['url'], title=entry['title'], path=path) else: file = download(entry['url'], path=path) tags = MP3(file) if 'artist' in entry and entry['artist']: tags['TPE1'] = TPE1(encoding=3, text=entry['artist']) if 'title' in entry and entry['title']: tags['TIT2'] = TIT2(encoding=3, text=entry['title']) if 'album' in entry and entry['album']: tags['TALB'] = TALB(encoding=3, text=entry['album']) if 'img' in entry and entry['img']: img = entry['img'].decode('base64') tags['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, data=img) tags.save(v2_version=3) return file
def write_to_mp3(): """Add metadata to MP3 file.""" audio = MP3(os.path.join(directory, song_filename), ID3=ID3) audio["TALB"] = TALB(encoding=3, text=song_properties["album"]) audio["TPE1"] = TPE1(encoding=3, text=song_properties["artist"]) audio["TIT2"] = TIT2(encoding=3, text=song_properties["song"]) audio["TCON"] = TCON(encoding=3, text=song_properties["genre"]) if valid_artwork(): audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime="image/jpeg", # image/jpeg or image/png type=3, # 3 is for the cover image desc="Cover", data=response.content, )) audio.save()
def song_meta(self, path, songInfo): ''' 编辑歌曲信息 :param path: :param songInfo: :return: ''' try: audio = MP3(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(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( encoding= 0, # 3 is for UTF8, but here we use 0 (LATIN1) for 163, orz~~~ mime='image/jpeg', # image/jpeg or image/png type=3, # 3 is for the cover(front) image data=self.read_image(songInfo['albumArt']))) # add artist name id3.add(TPE1(encoding=3, text=songInfo['songer'])) # add song name id3.add(TIT2(encoding=3, text=songInfo['songName'])) # add album name id3.add(TALB(encoding=3, text=songInfo['albumName'])) id3.save(v2_version=3)
def __embed_metatags(self, query, filename, genius_url): # search for song metadata music_info = self.__get_song_metadata(query, genius_url) # embed relevant tags using mutagen audio_file = File(filename) # embed title and artist info title = self.__get_title(music_info) artist = music_info['primary_artist']['name'] audio_file['TIT2'] = TIT2(encoding=3, text=[title]) audio_file['TPE1'] = TPE1(encoding=3, text=[artist]) # embed album info album_name, album_artist = self.__get_album_info(music_info) audio_file['TALB'] = TALB(encoding=3, text=[album_name]) audio_file['TPE2'] = TPE2(encoding=3, text=[album_artist]) # embed other tags audio_file['USLT::XXX'] = USLT(encoding=1, lang='XXX', desc='', text=music_info['lyrics']) audio_file['TRCK'] = TRCK(encoding=3, text=[music_info['track_number']]) try: artwork = requests.get(self.__get_cover_art_url(music_info), stream=True) audio_file['APIC:'] = APIC(encoding=3, mime="image/jpeg", type=3, desc='', data=artwork.raw.read()) except Exception as e: self.log(f"\tFailed to embed artwork for title: {title}", e) # save the new file audio_file.save() # return new title and filename return f'{artist} - {title}', self.__rename_file( title, artist, filename)
def __saveMp3__(self, coverPath): if self._handle.tags is None: self._handle.add_tags() self._handle.tags.add(TIT2(encoding=3, text=self.title)) self._handle.tags.add(TALB(encoding=3, text=self.album)) # self._handle.tags.add(TOPE(encoding=3, text=self.albumartist)) self._handle.tags.add(TPE1(encoding=3, text=self.artist)) self._handle.tags.add(TCOP(encoding=3, text=self.copyright)) self._handle.tags.add(TRCK(encoding=3, text=str(self.tracknumber))) # self._handle.tags.add(TRCK(encoding=3, text=self.discnum)) self._handle.tags.add(TCON(encoding=3, text=self.genre)) self._handle.tags.add(TDRC(encoding=3, text=self.date)) self._handle.tags.add(TCOM(encoding=3, text=self.composer)) self._handle.tags.add(TSRC(encoding=3, text=self.isrc)) self._handle.tags.add( USLT(encoding=3, lang=u'eng', desc=u'desc', text=self.lyrics)) self.__savePic__(coverPath) self._handle.save() return True
def add_metadata_to_song(file_path, cover_path, song): # 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( encoding= 0, # 3 is for UTF8, but here we use 0 (LATIN1) for 163, orz~~~ mime='image/jpeg', # image/jpeg or image/png type=3, # 3 is for the cover(front) image data=open(cover_path, 'rb').read())) # add artist name id3.add(TPE1(encoding=3, text=song['artists'][0]['name'])) # add song name id3.add(TIT2(encoding=3, text=song['name'])) # add album name id3.add(TALB(encoding=3, text=song['album']['name'])) # add song track number id3.add( TRCK(encoding=3, text='{}/{}'.format(song['no'], song['album']['size']))) id3.save(v2_version=3)
def tagFile(self, filename, metadata, track): audio = MP3(filename, ID3=ID3) try: audio.add_tags() except: return with open('album-art.jpg', 'rb') as file: image = file.read() audio.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=image)) audio.tags["TIT2"] = TIT2(encoding=3, text=track['title']) audio.tags["TALB"] = TALB(encoding=3, text=metadata['album']) audio.tags["TPE1"] = TPE1(encoding=3, text=metadata['artist']) audio.tags["TDRC"] = TDRC(encoding=3, text=unicode(metadata['year'])) audio.save()
def fixMetadata(path, filename): with open(filename) as fpin: for line in fpin: mp3file = line.strip() audio = MP3(path + mp3file + '.mp3', ID3=ID3) try: audio.add_tags() except error: pass while 1: new_name = input("EDIT>" + mp3file + ">") if new_name == "1" or new_name == "": title = (input("Enter new title : ") or mp3file) artist = input("Enter artist : ") audio.tags.add(TIT2(text=title)) audio.tags.add(TPE1(text=artist)) audio.save() break s_obj = spotifySearch(new_name) print(json.dumps(s_obj, indent=4, sort_keys=False)) if s_obj["image_url"] == "": continue else: opt = input("1 = yes : ") if opt == "1": audio.tags.add(TIT2(text=mp3file)) audio.tags.add(TPE1(text=s_obj["artists"])) audio.tags.add(TALB(text=s_obj["album"])) audio.tags.add(TDRC(text=(s_obj["release_date"][:4]))) audio.tags.add(TYER(text=(s_obj["release_date"][:4]))) audio.tags.add(TCON(text=s_obj["genres"])) audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime='image/png', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=urllib.request.urlopen(s_obj["image_url"]).read() ) ) audio.save() break