def slot_apply(self): self.ID3TagsToEdit = {} log.debug("Saving ID3 Data in cache...") self.ID3TagsToEdit['TIT2'] = TIT2(encoding=3, text=unicode( self.title.displayText())) self.ID3TagsToEdit['TPE1'] = TPE1(encoding=3, text=unicode( self.artist.displayText())) self.ID3TagsToEdit['TALB'] = TALB(encoding=3, text=unicode( self.album.displayText())) self.ID3TagsToEdit['TDRC'] = TDRC(encoding=3, text=unicode( self.date.displayText())) self.ID3TagsToEdit['COMM'] = COMM(encoding=3, text=unicode( config.id3tags_whitemark), desc='') lyrics = unicode(self.lyrics.toPlainText()).replace('\r\n', '\n').replace( '\n', '\r\n') if lyrics: if utils.isHebrew(lyrics): self.ID3TagsToEdit['USLT'] = USLT(encoding=3, lang=u'heb', desc=u'', text=lyrics) else: self.ID3TagsToEdit['USLT'] = USLT(encoding=3, lang=u'eng', desc=u'', text=lyrics) else: self.ID3TagsToEdit['USLT'] = '' if self.albumArt_task == 'add' and self.pix_path: with open(self.pix_path, 'rb') as f: data = f.read() self.ID3TagsToEdit['APIC'] = APIC(encoding=0, mime=utils.guess_image_mime_type( self.pix_path), type=0, desc="", data=data) elif self.albumArt_task == 'delete': self.ID3TagsToEdit[ 'APIC'] = '' # empty value doesn't add a new APIC tag. All other APIC tags are removed piror to insertion. self.close()
def writeMP3Tags(filename, tags, coverArtId): handle = MP3(filename, ID3=EasyID3) handle.delete() # label is not supported by easyID3, so we add it EasyID3.RegisterTextKey("label", "TPUB") # tracknumber and total tracks is one tag for ID3 tags['tracknumber'] = f'{str(tags["tracknumber"])}/{str(tags["totaltracks"])}' del tags['totaltracks'] for key, val in tags.items(): if key == 'artist': # Concatenate artists artists = val[0] # Main artist for artist in val[1:]: artists += ";" + artist handle[key] = artists elif key == 'lyrics': if 'uslt' in val: # unsynced lyrics handle.save() id3Handle = ID3(filename) id3Handle['USLT'] = USLT(encoding=3, text=val['uslt']) id3Handle.save(filename) handle.load(filename) # Reload tags else: handle[key] = str(val) handle.save() return True
def add_lyrics(file_path): """Add lyric tag to file""" audio = mutagen.File(file_path) try: tags = audio.tags except AttributeError: raise UnknownTypeError() else: if isinstance(tags, ID3): if tags.getall("USLT"): raise ExistingLyricsError() elif not (tags.get('TIT2') and tags.get('TPE1')): log.debug("Title or Artist missing") raise LyricsNotFoundError() else: lyrics = get_lyrics(tags.get('TIT2'), tags.get('TPE1')) log.debug("Adding lyrics") tags.add(USLT(encoding=3, text=lyrics)) tags.save(file_path) elif isinstance(tags, Vorbis): if 'LYRICS' in tags: raise ExistingLyricsError() elif ('TITLE' not in tags) or ('ARTIST' not in tags): log.debug("Title or Artist missing") raise LyricsNotFoundError() else: lyrics = get_lyrics(tags['TITLE'][0], tags['ARTIST'][0]) log.debug("Adding lyrics") tags['LYRICS'] = lyrics audio.save(file_path) else: raise UnsupportedTypeError(audio.mime[0][6:])
def edit_id3_tags(track, mp3_path, img_path): # Edit Artist/Title ID3 tags # http://stackoverflow.com/questions/18369188/python-add-id3-tags-to-mp3-file-that-has-no-tags logging.debug("Adding artist/title ID3 tags...") meta = mutagen.File(mp3_path, easy=True) meta["title"] = track.title meta["artist"] = track.artist meta["album"] = "SoundCloud" meta.save() # Embed description into lyrics field if track.description is not None: logging.debug("Writing description to lyrics field...") audio = ID3(mp3_path) audio.add( USLT(encoding=3, lang=u'eng', desc=u'desc', text=track.description)) audio.save() # Embed album art if track.artwork_url is not None: logging.debug("Adding album art...") audio = ID3(mp3_path) audio.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=open(img_path, "rb").read())) audio.save()
def changeTags(self): for song in self.songs: for file in self.files: if os.path.basename(file)[1:-4] == str(song['songId']): audio = EasyID3(file) audio['title'] = song['songName'].translate( str.maketrans('.?:$}', "#####")) audio['artist'] = ", ".join(song['artists']) audio['album'] = song['albumName'].translate( str.maketrans('.?:$}', "#####")) audio['date'] = song['releaseDate'] audio['genre'] = song['genre'] audio.save() fd = urllib.request.urlopen(song['albumImg']) 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=song['lyrics'])) audio.save() move( file, "C:/Users/user/OneDrive/음악/" + song['songName'].translate( str.maketrans('.?:$}', "#####")) + "-" + ", ".join(song['artists']) + ".mp3") break
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).raw.read())) for key, values in tags.items(): if key != 'APIC:cover': print('\t', key, ': ', values, sep='') tags.add(USLT(encoding=3, lang='eng', desc='aaa', text=lrc)) tags.save()
def addLyrics(path): """ Add's the lyrics for the provided file path """ # Create the tags if needed try: tags = ID3(path) except ID3NoHeaderError: tags = ID3() # Remove lyrics if they already exist if len(tags.getall(u"USLT")) != 0: tags.delall(u"USLT") song = searchForSong(tags[TITLE], tags[ARTIST] if tags[ARTIST] != "" else None) if song == None: print("Couldn't find the song for the path:\n{}".format(path)) return lyrics = scrapeLyrics(song) tags[u"USLT"] = (USLT(encoding=3, lang='ENG', text=lyrics)) tags.save(path) print("Done: {}".format(path))
def _embed_mp3_lyrics(audio_file, song_object): # ! setting the lyrics lyrics = song_object.lyrics USLTOutput = USLT(encoding=3, lang=u"eng", desc=u"desc", text=lyrics) audio_file["USLT::'eng'"] = USLTOutput return audio_file
def tag_file(fn, artist, album, title, lyrics, date, atype): try: audiofile = MP3(fn, ID3=EasyID3) audiofile.delete() audiofile.save() audiofile['title'] = title audiofile['album'] = album audiofile['artist'] = artist audiofile['albumartist'] = artist if date is not None: audiofile['date'] = date audiofile['discnumber'] = ['1/1'] if atype == 'Single': audiofile['tracknumber'] = ['1/1'] audiofile.save() audiofile = MP3(fn, ID3=ID3) audiofile.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=open('download.jpg', 'rb').read())) if lyrics is not None: audiofile.tags.add(USLT(lang='eng', text=lyrics)) audiofile.save() os.rename(fn, artist + ' - ' + title + '.mp3') os.remove('download.jpg') return (True) except Exception: return (False)
class ID3Tags: title = ID3TagItem('TIT2', lambda i: i.text[0], lambda i: TIT2(encoding=Encoding.UTF8, text=i)) album = ID3TagItem('TALB', lambda i: i.text[0], lambda i: TALB(encoding=Encoding.UTF8, text=i)) artist = ID3TagItem('TPE1', lambda i: i.text[0], lambda i: TPE1(encoding=Encoding.UTF8, text=i)) sync_lrc = ID3TagItem( 'SYLT', lambda i: i.text, lambda i: SYLT( encoding=Encoding.UTF8, lang='eng', format=2, type=1, text=i)) unsync_lrc = ID3TagItem( 'USLT', lambda i: i.text, lambda i: USLT(encoding=Encoding.UTF8, lang='eng', text=i)) url = ID3TagItem('WXXX', lambda i: i.url, lambda i: WXXX(encoding=Encoding.UTF8, url=i)) cover = ID3TagItem( 'APIC', lambda i: i.data, lambda i: 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, data=i)) def __init__(self, mp3path): self.file_path = mp3path try: self.tag = ID3(mp3path) except ID3NoHeaderError: self.tag = ID3() def save(self, file_path=None): file_path = file_path or self.file_path self.tag.save(file_path or self.file_path, v2_version=3)
def mp3_refresh(self, track_path: str) -> bool: try: audio = mp3.EasyMP3(track_path) tag_dict = {} for key in audio.tags: tag_dict[key] = audio.tags[key][0] artist, title = tag_dict['artist'], tag_dict['title'] title = title_prettify(title) lyrics = self.get_lyrics(artist, title) if lyrics: tags = ID3(track_path) uslt_output = USLT(text=lyrics) tags["USLT::'eng'"] = uslt_output tags.save(track_path) return True except Exception as e: logging.warning(f"EXCEPTION at {track_path}: {e}") return False
def add_details(file_name, song_title, artist, album, lyrics=""): ''' Adds the details to song ''' tags = EasyMP3(file_name) tags["album"] = album tags["title"] = song_title tags["artist"] = artist tags.save() tags = ID3(file_name) tags["USLT::'eng'"] = ( USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)) tags.save(file_name) try: rename(file_name, song_title + '.mp3') except FileNotFoundError: pass print("\n [*]Song name : %s \n [*]Artist : %s \n [*]Album : %s \n " % ( song_title, artist, album))
def set_file_tags(filename, tags): try: default_tags = ID3(filename) except ID3NoHeaderError: # Adding ID3 header default_tags = ID3() # Tag Breakdown # Track: TIT2 # OG Filename: TOFN # Artist - Song Title.MP3 # Artist: TOPE, TPE1, WOAR(official), TSO2(itunes), TPE2(band) # Lyrics: TEXT # Album: TOAL(original), TSO2(itunes), TSOA(sort), TALB # Genres: TCON # Year: TORY(release), TYER(record) # Publisher: TPUB, WPUB(info) default_tags["TOFN"] = TOFN(encoding=3, text=os.path.split(filename[0])[1]) # Original Filename default_tags["TIT2"] = TIT2(encoding=3, text=tags.song) # Title default_tags["TRCK"] = TRCK(encoding=3, text=tags.track_number) # Track Number # Artist tags default_tags["TOPE"] = TOPE(encoding=3, text=tags.artist) # Original Artist/Performer default_tags["TPE1"] = TPE1(encoding=3, text=tags.artist) # Lead Artist/Performer/Soloist/Group default_tags["TPE2"] = TPE2(encoding=3, text=tags.album_artist) # Band/Orchestra/Accompaniment # Album tags default_tags["TOAL"] = TOAL(encoding=3, text=tags.album) # Original Album default_tags["TALB"] = TALB(encoding=3, text=tags.album) # Album Name default_tags["TSO2"] = TSO2(encoding=3, text=tags.album) # iTunes Album Artist Sort # tags["TSOA"] = TSOA(encoding=3, text=tags.album[0]) # Album Sort Order key default_tags["TCON"] = TCON(encoding=3, text=tags.genres) # Genre default_tags["TDOR"] = TORY(encoding=3, text=str(tags.year)) # Original Release Year default_tags["TDRC"] = TYER(encoding=3, text=str(tags.year)) # Year of recording default_tags["USLT"] = USLT(encoding=3, text=tags.lyrics) # Lyrics default_tags.save(v2_version=3) # Album Cover if type(tags.album_cover) == str: r = requests.get(tags.album_cover, stream=True) r.raise_for_status() r.raw.decode_content = True with open('img.jpg', 'wb') as out_file: shutil.copyfileobj(r.raw, out_file) del r with open('img.jpg', 'rb') as albumart: default_tags.add(APIC( encoding=3, mime="image/jpg", type=3, desc='Cover', data=albumart.read())) elif type(tags.album_cover) == bytes: default_tags.add(APIC( encoding=3, mime="image/jpg", type=3, desc='Cover', data=tags.album_cover)) default_tags.save(v2_version=3)
def add_mp3_tags(fileobj, tags, cover=None, lyrics=None, image_mimetype='image/png'): handle = MP3(fileobj=fileobj) if 'artist' in tags: handle['TPE1'] = TPE1(text=tags['artist']) if 'title' in tags: handle['TIT2'] = TIT2(text=tags['title']) if 'album' in tags: handle['TALB'] = TALB(text=tags['album']) if 'albumartist' in tags: handle['TPE2'] = TPE2(text=tags['albumartist']) if 'genre' in tags: handle['TCON'] = TCON(genres=[tags['genre']]) if 'tracknumber' in tags: handle['TRCK'] = TRCK(text=tags['tracknumber']) if 'year' in tags: handle['TYER'] = TYER(text=tags['year']) if 'date' in tags: handle['TDAT'] = TDAT(text=tags['date']) if 'bpm' in tags: handle['TBPM'] = TBPM(text=tags['bpm']) if 'isrc' in tags: handle['TSRC'] = TSRC(text=tags['isrc']) if 'explicit' in tags: handle['TXXX'] = TXXX(text=tags['explicit']) if lyrics: handle['USLT'] = USLT(text=lyrics) if cover: handle['APIC'] = APIC(data=cover, mime=image_mimetype) handle.save(fileobj) fileobj.seek(0)
def add_metadata(filename, md): try: tags = ID3(filename) except mutagen.id3.ID3NoHeaderError: file = mutagen.File(filename) file.add_tags() tags = file if 'title' in md: tags["TIT2"] = TIT2(text=md['title']) if 'artist' in md: tags["TPE1"] = TPE1(text=md['artist']) if 'album' in md: tags["TALB"] = TALB(text=md['album']) if 'album_artist' in md: tags["TPE2"] = TPE2(text=md['album_artist']) if 'track_number' in md: track_number = str(md['track_number']) if 'track_count' in md: track_number += '/' + str(md['track_count']) tags["TRCK"] = TRCK(encoding=3, text=track_number) if 'genre' in md: tags["TCON"] = TCON(text=md['genre']) if 'year' in md: tags["TDRC"] = TDRC(text=md['year']) if 'comment' in md: tags["COMM"] = COMM(text=md['comment'], lang='eng') if 'lyrics' in md: tags["USLT"] = USLT(text=md['lyrics']) if 'composer' in md: tags["TCOM"] = TCOM(text=md['composer']) for key, value in md.items(): whitespace = ' ' * (10 - len(key)) log(' ' + key + ':' + whitespace + pformat(value)) tags.save(filename)
def imgSave(audioPath, imgUrl, letra): #Abre o audio audio = ID3(audioPath) #Abre a imagem res = req.get(imgUrl) res.raise_for_status() #Faz o download da imagem imgPath = 'image.' + imgUrl[-3:] imageFile = open(imgPath, 'wb') for chunk in res.iter_content(100000): imageFile.write(chunk) imageFile.close() #Abre a imagem baixada imageData = open(imgPath, 'rb').read() #Salva a imagem no arquivo de audio audio.add(APIC(3, 'image/jpeg', 3, 'Front cover', imageData)) #Salva a letra if letra != None: audio.add(USLT(encoding=3, lang=u'eng', desc=u'desc', text=letra)) #Salva e fecha o arquivo de audio audio.save(v2_version=3) #Deleta a imagem baixada os.remove(imgPath)
def write2tag(tag, lyric): ''' :param tag: object created by 'ID3(file)' ''' arr = parse_synced_lyric(lyric) if len(arr) > 0: #synced lyric """ 'SYLT' is not displayed. if len(tag.getall('SYLT'))>0: tag.delall('SYLT') tag.add( SYLT(encoding=3,lang=u'eng',desc=u'desc', format=2, #time format=mill seconds type=1, #type=lyric text=arr #[(text of lyric,start_time)] ) ) """ if len(tag.getall('TXXX:LIRICS')) > 0: tag.delall('TXXX:LIRICS') tag.add(TXXX(encoding=3, desc='LYRICS', text=[lyric])) else: #save tag to unsynced lyric if len(tag.getall('USLT')) > 0: tag.delall('USLT') tag.add(USLT(encoding=3, lang='eng', desc='desc', text=lyric)) try: tag.save() except Exception as e: msg = "error at saving mp3.:" + str(e) print(msg) logging.error(msg)
def apply_meta(self, filename: str, meta: dict): album_cover = self._album_cover_download( meta["album"]["images"][0]["url"] ) album_artists = ", ".join(meta["album"]["artists"]) artists = ", ".join(meta["artist"]) lyric = LyricsSearcher(meta["name"], artists).search() tag = ID3(filename) tag["TIT2"] = TIT2(3, meta["name"]) # Title tag["TPE1"] = TPE1(3, artists) # Artist tag["TPE2"] = TPE2(3, album_artists) # Album Artist tag["TALB"] = TALB(3, meta["album"]["name"]) # Album Title tag["TRCK"] = TRCK(3, str(meta["track_number"])) # Track Number tag["TYER"] = TYER( 3, meta["album"]["released_at"].split("-")[0] ) # Released Year tag["APIC"] = APIC( encoding=3, mime="image/jpeg", type=3, desc="Album Cover", data=album_cover, ) # Album Cover if lyric is not None: tag["USLT"] = USLT(3, desc="", text=lyric) tag.save(v2_version=3) # ID3 os.rename( filename, self._safe_name("{} - {}".format(artists, meta["name"])) + ".mp3", )
def embedd_lyrics(fileName, lyrics): try: tags = ID3(fileName) except ID3NoHeaderError: tags = ID3() if not (len(tags.getall(u"USLT::'en'")) == 0): tags.delall(u"USLT::'en'") tags.save(fileName) # Add lyrics to tag object try: tags[u"USLT::'eng'"] = (USLT(encoding=3, lang=u'eng', text=lyrics)) except: print("Error inserting lyrics for: " + ntpath.basename(fileName), file=sys.stderr) return False try: tags.save(fileName, v2_version=3) except Exception: print("Error modifying mp3 file", file=sys.stderr) return False return True
def Embed(fname,fn, failed, embedded): fname = os.path.join(fpath, fn) fail = 0 embed = 0 print(fname) if fname.lower().endswith('.mp3'): # tags=ID3(fname) # if len(tags.getall('USLT::\'en\'')) != 0: # tags.delall('USLT::\'en\'') # print("removing lyrics") # tags.save(fname) # tags.save() tags["USLT"] = USLT(encoding=0, lang="eng", text=lyrics) tags.save(fname) tags.save() run_once = 2 # print(tags['USLT']) lol = str(tags['USLT']) # print(tags['USLT']) if (len(lol) < 50): print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<=FAILED=' + str(failed) + '>>>>>>>>>>>>>>>>>>>>>>') fail = 1 else: print('==========================>Lyrics Embedded=' + str(embedded) + '=================>') embed = 1 return fail, embed
def find(artist, title, file): session = requests.session() headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} url = "https://www.musixmatch.com/lyrics/" + artist.replace(' ', '-') + "/" + title.replace(' ', '-') response = session.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") lyrics = "" items = soup.findAll('p', {'class': 'mxm-lyrics__content'}) if len(items) == 0: print("\033[91m" + "No lyrics found for " + artist + " - " + title + "\n" + "URL: " + url + "\033[0m") return for item in items: lyrics += item.text print("Adding lyrics for " + artist + " - " + title) try: tags = ID3(file) except ID3NoHeaderError: print("\033[91m" + "No ID3 header found for " + artist + " - " + title + "\033[0m") tags['USLT::eng'] = (USLT(encoding=3, lang='eng', text=lyrics)) tags.save(file) print("Lyrics successfully added for " + artist + " - " + title)
def as_mp3(self): """ Embed metadata to MP3 files. """ music_file = self.music_file #print(music_file) meta_tags = self.meta_tags #print(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 ''' mera code adding dummy tags''' try: tags = ID3(music_file) except ID3NoHeaderError: tags = ID3() tags.save(music_file) audiofile = EasyID3(music_file) self._embed_basic_metadata(audiofile, preset=TAG_PRESET) 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['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 _embed_mp3_lyrics(audio_file, song_obj): # ! setting the lyrics lyrics = song_obj.get_lyrics() USLTOutput = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics) audio_file["USLT::'eng'"] = USLTOutput return audio_file
def setSongInfo(song_path, music_info, lyr_path, pic_path, media_type): lyrics = open(lyr_path, encoding='utf-8').read().strip() # try to find the right encoding for enc in ('utf8', 'iso-8859-1', 'iso-8859-15', 'cp1252', 'cp1251', 'latin1'): try: lyrics = lyrics.decode(enc) print(enc, ) break except: pass if media_type == 'mp3': # 用eyed3库只支持英文歌名,对utf-8格式的文件无法修改;所以使用mutagen库替代修改mp3信息 # 传入mp3、jpg的url路径以及其他字符串 tags = ID3(song_path) tags.update_to_v23() # 把可能存在的旧版本升级为2.3 # 插入歌名 tags['TIT2'] = TIT2(encoding=3, text=[music_info['name']]) # 插入歌曲艺术家 tags['TPE1'] = TPE1(encoding=3, text=[music_info['artist']]) # 插入专辑名称 tags['TALB'] = TALB(encoding=3, text=[music_info['albumName']]) # 插入专辑公司 # tags['TCOP'] = TCOP(encoding=3, text=[music_info['Company']]) # 插入声道数 tags['TRCK'] = TRCK(encoding=3, text=[music_info['trackNumber']]) # 插入发行时间 tags['TYER'] = TYER(encoding=3, text=[music_info['publishYear']]) tags["TDRC"] = TDRC(encoding=3, text=music_info['publishYear']) # 插入专辑图片 # response = urllib.request.urlopen(mp3_header_info['albumPicDownUrl']) # tags['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=response.data) with open(pic_path, 'rb') as img: tags['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=img.read()) # 插入歌词 # remove old unsychronized lyrics if len(tags.getall(u"USLT::'en'")) != 0: mylogger.info("Removing Lyrics.") tags.delall(u"USLT::'en'") tags.save() # tags.add(USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)) # apparently the description is important when more than one # USLT frames are present tags[u"USLT::'eng'"] = (USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)) tags.save() elif media_type == 'm4a': tags = MP4(song_path).tags tags['\xa9nam'] = music_info['name'] tags['\xa9alb'] = music_info['albumName'] tags['\xa9ART'] = music_info['artist'] tags['\xa9day'] = music_info['pub_time'] tags['\xa9cmt'] = music_info['subtitle'] tags['\xa9gen'] = music_info['genre'] with open(pic_path, 'rb') as img: tags["covr"] = [MP4Cover(img.read(), imageformat=MP4Cover.FORMAT_JPEG)] tags.save(song_path) else: mylogger.error("%s 类型不支持." % song_path)
def process(file, process_all=False, remove_previous=True): """ Fetch and Embed lyrics into a file. """ try: mp3 = MP3(file) except: print("Couldn't read: %s" % file) return # Skip files that are not tagged by MusicBrainz if (not process_all and not is_tagged(mp3)): print("Not tagged: %s " % file) return # Skip files that already have embedded lyrics & user asked us not to overwrite if (any(k.startswith("USLT") for k in list(mp3.keys())) and not remove_previous): print("Lyrics already present: %s " % file) return sys.stdout.write("Processing: %s " % file) sys.stdout.flush() # Use friendly names for ID3 tags # http://picard.musicbrainz.org/docs/mappings/ # TODO: This mapping will allow us to support formats other than MP3 tags = {} tags['artist'] = str(mp3.get('TPE1', '')) tags['album'] = str(mp3.get('TALB', '')) tags['title'] = str(mp3.get('TIT2', '')) tags['year'] = str(mp3.get('TYER', '0')) tags['track_no'] = str(mp3.get('', '0')) # Magic happens here lyrics = "" for name, provider in gen_providers().items(): try: lyrics = provider.fetch(tags) except: continue # :'( if not lyrics: sys.stdout.write(" \033[31m[✖]\033[0m") return # Remove all previous USLT tags if remove_previous: for key in list(mp3.keys()): if key.startswith("USLT"): del mp3[key] # Add new lyrics # TODO: Support languages other than English mp3[u"USLT::'en'"] = (USLT(encoding=3, lang=u'eng', desc=u'', text=lyrics)) mp3.save() sys.stdout.write(" \033[32m[✔]\033[0m")
def mount_lyrics(lyrics, path): tags = ID3(path) # tags['unsyncedlyrics'] = lyrics tags[u"USLT::'eng'"] = (USLT(encoding=3, lang='eng', desc=u'desc', text=lyrics)) tags.save()
def write_tags(song, data): try: tag = FLAC(song) tag.delete() images = Picture() images.type = 3 images.data = data["image"] tag.clear_pictures() tag.add_picture(images) tag["lyrics"] = data["lyric"] except FLACNoHeaderError: try: tag = File(song, easy=True) tag.delete() except: if isfile(song): remove(song) raise exceptions.TrackNotFound("") except NOTVALIDSONG: raise exceptions.TrackNotFound("") 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["lyricist"] = data["lyricist"] tag.save() try: audio = ID3(song) audio.add( APIC( encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=data["image"], )) audio.add( USLT(encoding=3, lang=u"eng", desc=u"desc", text=data["lyric"])) audio.save() except ID3NoHeaderError: pass
def as_mp3(self, path, metadata, cached_albumart=None): """ Embed metadata to MP3 files. """ logger.debug('Writing MP3 metadata to "{path}".'.format(path=path)) # 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(path) self._embed_basic_metadata(audiofile, metadata, "mp3", preset=TAG_PRESET) audiofile["media"] = metadata["type"] audiofile["author"] = metadata["artists"][0]["name"] audiofile["lyricist"] = metadata["artists"][0]["name"] audiofile["arranger"] = metadata["artists"][0]["name"] audiofile["performer"] = metadata["artists"][0]["name"] provider = metadata["provider"] audiofile["website"] = metadata["external_urls"][provider] audiofile["length"] = str(metadata["duration"]) if metadata["publisher"]: audiofile["encodedby"] = metadata["publisher"] if metadata["external_ids"]["isrc"]: audiofile["isrc"] = metadata["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 in the linked source file represents an id3 tag audiofile = ID3(path) if metadata["year"]: audiofile["TORY"] = TORY(encoding=3, text=metadata["year"]) audiofile["TYER"] = TYER(encoding=3, text=metadata["year"]) if metadata["publisher"]: audiofile["TPUB"] = TPUB(encoding=3, text=metadata["publisher"]) provider = metadata["provider"] audiofile["COMM"] = COMM(encoding=3, text=metadata["external_urls"][provider]) if metadata["lyrics"]: audiofile["USLT"] = USLT(encoding=3, desc=u"Lyrics", text=metadata["lyrics"]) if cached_albumart is None: cached_albumart = urllib.request.urlopen( metadata["album"]["images"][0]["url"]).read() albumart.close() try: audiofile["APIC"] = APIC( encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=cached_albumart, ) except IndexError: pass audiofile.save(v2_version=3)
def UpdateLyrics(self, file_paths): i = 0 lyrics = list(self.lyrics_MA.values()) print(lyrics) for item in file_paths: song = ID3(item) song.add(USLT(text=lyrics[i])) song.save() i = i + 1
def storeLyricsToSong(pathSong, lyrics): if(pathSong.lower().endswith(".mp3")): song = ID3(pathSong) song["USLT::'eng'"] = (USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)) song.save() #M4A elif(pathSong.lower().endswith(".m4a")): song = MP4(pathSong) song["©lyr"] = lyrics song.save()
def test_USLT(self): from mutagen.id3 import USLT frame = USLT(encoding=0, lang="foo", desc="d", text="t") self.assertEqual(frame.HashKey, "USLT:d:foo") frame._pprint()
def test_hash(self): frame = USLT(encoding=0, lang="foo", desc="d", text="t") self.assertEqual(frame.HashKey, "USLT:d:foo") frame._pprint()