def _audio_talb(atuple): audio, atag, advanced, _, _ = atuple if advanced: param = ast.literal_eval(atag) audio.add(TALB(3, param[1])) else: audio.add(TALB(3, atag))
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(WXXX(encoding=3, desc=u'xiami_song_url', text=info['song_url'])) #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=u'\n\n'.join( [info['song_url'], info['album_description']]))) id3.add( APIC(encoding=3, mime=u'image/jpeg', type=3, desc=u'Front Cover', data=self.get_cover(info))) id3.save(file_name)
def writeAlbumInfo(self, album_card_element): """ 写入专辑文字信息 """ album_card = album_card_element.text print(album_card, '\n') # 创建正则表达式来匹配所需信息 rex1 = r'专辑名:(.+)\n' rex2 = r'发行时间:(.{4})-' Match_album_name = re.match(rex1, album_card) Match_album_year = re.search(rex2, album_card) # 写入专辑名 if Match_album_name: album_name = Match_album_name.group(1) # 写入专辑标题 if self.suffix == 'mp3': self.id_card['TALB'] = TALB(encoding=3, text=album_name) elif self.suffix == 'flac': self.id_card['album'] = album_name elif self.suffix == 'mp4': self.id_card['©alb'] = [album_name] # 写入专辑年份 if Match_album_year: album_year = Match_album_year.group(1) if self.suffix == 'mp3': self.id_card['TDRC'] = TDRC(encoding=3, text=album_year) elif self.suffix == 'flac': self.id_card['year'] = album_year elif self.suffix == 'mp4': self.id_card['©day'] = [album_year]
def id3Tag(self, file, title, album, artist, url): def getImageData(url): response = requests.get(url) img = Image.open(BytesIO(response.content)) (x, y) = img.size fixed = 150 out = img.resize((fixed, int(y * fixed / x)), Image.ANTIALIAS) imgByteArr = BytesIO() out.save(imgByteArr, format='JPEG') return imgByteArr.getvalue() audio = ID3(file) # Title if title: audio.add(TIT2(encoding=3, text=title)) # Album if album: audio.add(TALB(encoding=3, text=album)) # Artist if artist: audio.add(TPE1(encoding=3, text=artist)) if url: audio.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=getImageData(url) # data=open('resize.jpg','rb').read() #data=requests.get("https://www.baidu.com/img/bd_logo1.png?where=super").content )) audio.save()
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 write_id3(pod_path, file_name, titles, episode_num, season_num, alb, albart, art): print(season_num) for file_name_entry in file_name: file_name_index = file_name_entry.index(file_name_entry) try: audio = ID3(pod_path + file_name_entry) audio.delete() audio = ID3() except ID3NoHeaderError: audio = ID3() audio.add(TIT2(encoding=3, text=titles[file_name_index])) if len(episode_num) != 0: audio.add(TRCK(encoding=3, text=episode_num[file_name_index])) else: print("No Ep Num") if len(season_num) != 0: audio.add(TPOS(encoding=3, text=season_num[file_name_index])) else: print("No Sn Num") audio.add(TPE1(encoding=3, text=art)) audio.add(TPE2(encoding=3, text=albart)) audio.add(TALB(encoding=3, text=alb)) audio.save(pod_path + file_name_entry)
def to_id3_tags(self, audio_path): """Loads an MP3 file and adds ID3v2.4 tags based on the given discogs entry""" audio = ID3(audio_path, v2_version=4) # Set album art album_art_url = self.get_album_art_url() if album_art_url: r = requests.get(album_art_url) audio.add(APIC( encoding=3, mime='image/jpeg', type=3, desc='Cover', data=r.content )) del r # Set title audio.add(TIT2(encoding=3, text=[self.track.title])) # Set artists audio.add(TPE1(encoding=3, text=self.get_artists())) # Set album audio.add(TALB(encoding=3, text=[self.get_release_title()])) # Set track number audio.add(TRCK(encoding=3, text=[self.track.position])) # Set labels labels = list(self.get_labels()) if len(labels) > 0: audio.add(TPUB(encoding=3, text=labels[0:1])) # Set genres audio.add(TCON(encoding=3, text=self.get_genres())) # Set year audio.add(TYER(encoding=3, text=[self.get_year()])) # for backwards compatibility with v2.3 # The timestamp fields are based on a subset of ISO 8601. When being as # precise as possible the format of a time string is # yyyy-MM-ddTHH:mm:ss (year, "-", month, "-", day, "T", hour (out of # 24), ":", minutes, ":", seconds), but the precision may be reduced by # removing as many time indicators as wanted. Hence valid timestamps # are # yyyy, yyyy-MM, yyyy-MM-dd, yyyy-MM-ddTHH, yyyy-MM-ddTHH:mm and # yyyy-MM-ddTHH:mm:ss. All time stamps are UTC. For durations, use # the slash character as described in 8601, and for multiple non- # contiguous dates, use multiple strings, if allowed by the frame # definition. audio.add(TDRL(encoding=3, text=[self.get_year()])) audio.add(TDOR(encoding=3, text=[self.get_year()])) # Set tagging time # aka right now # for completeness sake audio.add(TDTG(encoding=3, text=[datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M')])) # Write to disk audio.save()
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 modified_id3(self, file_name, info): ''' 给歌曲增加id3 tag信息 :file_name 待修改的歌曲完整地址 :info 歌曲信息 :return None ''' if not os.path.exists(file_name): return None 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(COMM(encoding=3, desc=u'Comment', text=info['song_url'])) http = requests.urllib3.PoolManager() with http.request('GET', info['album_pic_url'], preload_content=False) as r, open('img.jpg', 'wb') as out_file: shutil.copyfileobj(r, out_file) img = open('img.jpg', 'rb') id3['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=img.read()) id3.save(file_name)
def writeAlbumNameYear(self) -> bool: """ 检查是否需要写入丢失的年份和专辑名 """ isModified = False if not self.album: isModified = True self.album = self.browser.find_element_by_class_name( 'data__name_txt').text if self.suffix == 'mp3': self.id_card['TALB'] = TALB(encoding=3, text=self.album) elif self.suffix == 'flac': self.id_card['album'] = self.album elif self.suffix == 'mp4': self.id_card['©alb'] = [self.album] if not self.albumyear: isModified = True self.albumyear = self.browser.find_element_by_css_selector( 'ul.data__info >li:nth-of-type(3)').text rex = r'发行时间:(\d{4})' Match = re.match(rex, self.albumyear) if self.suffix == 'mp3' and Match: self.id_card['TDRC'] = TDRC(encoding=3, text=Match.group(1)) elif self.suffix == 'flac' and Match: self.id_card['year'] = Match.group(1) elif self.suffix == 'mp4' and Match: self.id_card['©day'] = [Match.group(1)] return isModified
def applyTrackMetadata(self): audio_file = ID3(self.file_path) # album cover image album_cover_art = urlopen(self.track.cover) audio_file['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=album_cover_art.read()) # album name audio_file['TALB'] = TALB(encoding=3, text=self.track.album_name) # album release year audio_file['TYER'] = TYER(encoding=3, text=self.track.release_date.split('-')[0]) # album artist audio_file['TPE2'] = TPE2(encoding=3, text=self.track.album_artist.split(';')) # track name audio_file['TIT2'] = TIT2(encoding=3, text=self.track.name) # track number audio_file['TRCK'] = TRCK(encoding=3, text=str(self.track.number)) # track artist name audio_file['TPE1'] = TPE1(encoding=3, text=self.track.featured_artists.split(';')) album_cover_art.close() audio_file.save(v2_version=3) self.SUCCESS = True
def modify_mp3_tag(song, song_path, image_path, genreArg): # Set genre genre = None if genreArg is None or genreArg.strip() == "": # Try extracting genre from existing tag try: tag = ID3(song_path) # will call load() on the path genre = tag.get("TCON").genres[0] if tag.get("TCON") else None except ID3NoHeaderError: pass else: genre = genreArg # Set genre to default if genre could not be extracted genre = DEFAULT_GENRE if genre is None or genre.strip() == "" else genre # Create empty tag and add frames to it tag = ID3() tag.add(TIT2(encoding=3, text=unicode(song.title) )) # TITLE tag.add(TRCK(encoding=3, text=unicode(int(song.track_num)))) # TRACK tag.add(TPE1(encoding=3, text=unicode(song.artist) )) # ARTIST tag.add(TPE2(encoding=3, text=unicode(song.artist) )) # ALBUMARTIST tag.add(TALB(encoding=3, text=unicode(song.album) )) # ALBUM tag.add(TYER(encoding=3, text=unicode(song.year) )) # YEAR tag.add(TDRC(encoding=3, text=unicode(song.year) )) # YEAR tag.add(TCON(encoding=3, text=unicode(genre) )) # GENRE if image_path: image_data = open(image_path, 'rb').read() image_type = image_path.split('.')[-1] # get the file extension without dot tag.add(APIC(3, "image/"+image_type, 3, 'Album Cover', image_data)) # Album Artwork tag.save(song_path, v2_version=3) # write the tag as ID3v2.3
def set(self,property,value): ''' Set value of given property. 1) Make sure value is valid. 2) check that property is valid. 3) check that property exists. 4) either modify or remove property. See self.tags for valid properties. ''' if(type(value)!=str): value = str(value) print("WARNING: value type of "+property+" has been corrected to 'str'") # ensure that property is valid assert property in self.tags,'Invalid property "{}"'.format(property) # check if property in object. if not, create it. if(self._d[property] not in self.dat.keys()): # property doesn't already exist in metadata if(property=='title'):self.dat.add(TIT2(encoding=3,text=value)) elif(property=='artist'): self.dat.add(TPE1(encoding=3,text=value)) elif(property=='album'): self.dat.add(TALB(encoding=3,text=value)) elif(property=='track'): self.dat.add(TRCK(encoding=3,text=value)) elif(property=='genre'): self.dat.add(TCON(encoding=3,text=value)) elif(property=='year'): self.dat.add(TDRC(encoding=3,text=str(value))) elif(property=='comment'): self.dat.add(COMM(encoding=3,lang='eng',text=value)) else: raise Exception('Invalid property to add') elif(value == ''): # user wants to clear the tag, so remove from object self.dat.pop(self._d[property]) elif(property=='year'): # having issues with year value. will specifically use 'add' self.dat.add(TDRC(encoding=3,text=str(value))) else: # simply modify the property self.dat[self._d[property]].text[0] = value return True
def write_id3_tags(self, file_name): """Writes ID3 tags from out music file into given MP3 file Args: :file_name """ try: tags = ID3(file_name) except ID3NoHeaderError: # Adding ID3 header tags = ID3() tags[self.TAG_TITLE] = TIT2(encoding=3, text='{} (Mp3VoiceStamp)'.format( self.title)) tags[self.TAG_ALBUM_TITLE] = TALB(encoding=3, text=self.album_title) tags[self.TAG_ALBUM_ARTIST] = TPE2(encoding=3, text=self.album_artist) tags[self.TAG_ARTIST] = TPE1(encoding=3, text=self.artist) tags[self.TAG_COMPOSER] = TCOM(encoding=3, text=self.composer) tags[self.TAG_TRACK_NUMBER] = TRCK(encoding=3, text=self.track_number) tags[self.TAG_ORIGINAL_FILENAME] = TOFN(encoding=3, text=self.file_name) tags[self.TAG_SOFTWARE] = TSSE(encoding=3, text='{app} v{v} {url}'.format( app=APP_NAME, v=VERSION, url=APP_URL)) tags.save(file_name)
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 addtag(fname, m_song, m_album, m_artist, m_singer, m_cover, m_year='', m_trackid='', m_cd=''): '''Add Tag for MP3''' ml = mylogger(logfile, get_funcname()) try: tags = ID3(fname) except ID3NoHeaderError: ml.dbg("Adding ID3 header on " + m_trackid) tags = ID3() tags["TIT2"] = TIT2(encoding=3, text=m_song) tags["TALB"] = TALB(encoding=3, text=m_album) tags["TPE2"] = TPE2(encoding=3, text=m_artist) #album artist #tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=u'mutagen comment') tags["TPE1"] = TPE1(encoding=3, text=m_singer) # singer #tags["TCOM"] = TCOM(encoding=3, text=u'mutagen Composer') #tags["TCON"] = TCON(encoding=3, text=u'mutagen Genre') tags["TDRC"] = TDRC(encoding=3, text=m_year) tags["TRCK"] = TRCK(encoding=3, text=str(m_trackid)) tags["TPOS"] = TPOS(encoding=3, text=m_cd) if m_cover != '': with open(m_cover, 'rb') as c: cover = c.read() #prepare for tag tags["APIC"] = APIC(encoding=3, mime=u'image/png', type=3, desc=u'Cover', data=cover) tags.save(fname, v2_version=3)
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 insert_tags(filepath, tags): """Using mutagen inject tags inside mp3 file :param filepath: path to file :type filepath: str :param tags: dict of tags :type tags: dict """ try: file = ID3(filepath) except ID3NoHeaderError: file = ID3() for key in tags: if key == 'album': file['TALB'] = TALB(encoding=3, text=tags[key]) elif key == 'artist': file['TPE1'] = TPE1(encoding=3, text=tags[key]) elif key == 'title': file['TIT2'] = TIT2(encoding=3, text=tags[key]) elif key == 'image': file.add( APIC(3, 'image/jpeg', 3, 'Front cover', get_image_bytes_from_url(tags[key]))) elif key == 'release_date': file['TDRC'] = TDRC(encoding=3, text=tags[key]) elif key == 'number': file['TRCK'] = TRCK(encoding=3, text=str(tags[key])) file.save(filepath)
def write_id3_single_file(path, filename, title, episode, season, album, album_artist, artist): print(episode) print(season) try: audio = ID3(path + filename) audio.delete() audio = ID3() except ID3NoHeaderError: audio = ID3() audio.add(TIT2(encoding=3, text=title)) if episode != '': audio.add(TRCK(encoding=3, text=episode)) else: print('No Episode Number') if season != '': audio.add(TPOS(encoding=3, text=season)) else: print('No Season Number') audio.add(TPE1(encoding=3, text=artist)) audio.add(TPE2(encoding=3, text=album_artist)) audio.add(TALB(encoding=3, text=album)) audio.save(path + filename)
def modifySongInfo(id_card, songInfo: dict): """ 从字典中读取信息并修改歌曲的标签卡信息 """ if songInfo['suffix'] == '.mp3': id_card['TRCK'] = TRCK(encoding=3, text=songInfo['tracknumber']) id_card['TIT2'] = TIT2(encoding=3, text=songInfo['songName']) id_card['TDRC'] = TDRC(encoding=3, text=songInfo['year'][:4]) id_card['TPE1'] = TPE1(encoding=3, text=songInfo['songer']) id_card['TPE2'] = TPE2(encoding=3, text=songInfo['songer']) id_card['TALB'] = TALB(encoding=3, text=songInfo['album']) id_card['TCON'] = TCON(encoding=3, text=songInfo['tcon']) elif songInfo['suffix'] == '.flac': id_card['tracknumber'] = songInfo['tracknumber'] id_card['title'] = songInfo['songName'] id_card['year'] = songInfo['year'][:4] id_card['artist'] = songInfo['songer'] id_card['album'] = songInfo['album'] id_card['genre'] = songInfo['tcon'] elif songInfo['suffix'] == '.m4a': # m4a写入曲目时还需要指定总曲目数 tag = TinyTag.get(id_card.filename) trackNum = int(songInfo['tracknumber']) trackTotal = 1 if not tag.track_total else int(tag.track_total) trackTotal = max(trackNum, trackTotal) id_card['trkn'] = [(trackNum, trackTotal)] id_card['©nam'] = songInfo['songName'] id_card['©day'] = songInfo['year'][:4] id_card['©ART'] = songInfo['songer'] id_card['aART'] = songInfo['songer'] id_card['©alb'] = songInfo['album'] id_card['©gen'] = songInfo['tcon']
def add_audio_tags(self, filename: str, info: dict): audio = MP3(filename) tags = { # Title/songname/content description 'TIT2': TIT2(encoding=3, text=info.get('track', '')), # Lead performer(s)/Soloist(s) 'TPE1': TPE1(encoding=3, text=info.get('artist', '')), # Date 'TDRC': TDRC(encoding=3, text=f'{info.get("release_year","")}'), # Content type (genre) 'TCON': TCON(encoding=3, text=info.get('genre', '')), # Album/Movie/Show title 'TALB': TALB(encoding=3, text=info.get('album', '')), # Track number/Position in set 'TRCK': TRCK(encoding=3, text=info.get('track_number', '')), # Comments 'COMM': COMM(encoding=3, text=f'https://youtu.be/{info.get("id", "")}'), } audio.update(tags) audio.save()
def setData(path, song): meta = ID3(path) meta.delete() meta.add(TIT2(encoding=3, text=song.track)) meta.add(TPE1(encoding=3, text=song.artist)) meta.add(TPE2(encoding=3, text=song.artist)) meta.add(TALB(encoding=3, text=song.album)) meta.add(TCON(encoding=3, text=song.genre)) meta.add(TRCK(encoding=3, text=song.track_number + '/' + song.track_count)) meta.add(TPOS(encoding=3, text=song.disc_number + '/' + song.disc_count)) meta.add(TDRC(encoding=3, text=song.release_date[0:4])) meta.save() # Embed cover-art in ID3 metadata meta = MP3(path, ID3=ID3) imgURL = song.artwork_url dir = Path.home() / 'Downloads' / 'Music' / 'CoverArt' os.system('mkdir -p %s' % (dir)) imgPath = os.path.join(dir, 'cover.jpg') response = requests.get(imgURL) img = Image.open(io.BytesIO(response.content)) img.save(imgPath) meta.tags.add( APIC(encoding=3, mime='image/jpg', type=3, desc=u'Cover', data=open(imgPath, 'rb').read())) meta.save() shutil.rmtree(dir)
def set_id3(self, path, resolution=480): """ Assigns the ID3 metadata of the MP3 file Args: path: The path of the converted MP3 file resolution: The target resolution of the cover-art """ tags = ID3(path) tags.delete() tags.add(TIT2(encoding=3, text=self.track)) tags.add(TPE1(encoding=3, text=self.artist)) tags.add(TPE2(encoding=3, text=self.artist)) tags.add(TALB(encoding=3, text=self.album)) tags.add(TCON(encoding=3, text=self.genre)) tags.add( TRCK(encoding=3, text=self.track_number + '/' + self.track_count)) tags.add( TPOS(encoding=3, text=self.disc_number + '/' + self.disc_count)) tags.add(TDRC(encoding=3, text=self.release_date[0:4])) # Embed cover-art in ID3 metadata img_path = self.get_cover_image(resolution) tags.add( APIC(encoding=3, mime='image/jpg', type=3, desc=u'Cover', data=open(img_path, 'rb').read())) tags.save()
def start(self): songinfo, session, headers = self.songinfo, self.session, self.headers filename = os.path.join(songinfo['savedir'], songinfo['savename']+'.'+songinfo['ext']) cover_file = None checkDir(songinfo['savedir']) if os.path.exists(filename): print('already downloaed, skip') return True try: if songinfo['cover_url']: cover_file = os.path.join(songinfo['savedir'], "%s - cover.jpg" % filterBadCharacter(songinfo['album'])) if not os.path.exists(cover_file): with open(cover_file, 'wb') as f: r = session.get(songinfo['cover_url'], headers=headers) f.write(r.content) f.close() is_success = False with closing(session.get(songinfo['download_url'], headers=headers, stream=True, verify=False)) as response: total_size = int(response.headers['content-length']) chunk_size = 1024 if response.status_code == 200: label = '[FileSize]: %0.2fMB' % (total_size/1024/1024) with click.progressbar(length=total_size, label=label) as progressbar: with open(filename, "wb") as fp: for chunk in response.iter_content(chunk_size=chunk_size): if chunk: fp.write(chunk) progressbar.update(chunk_size) is_success = True # ensure there's ID3 tag in mp3 file if filename.endswith('mp3'): from mutagen.mp3 import MP3 from mutagen.id3 import TPE1, TALB, TIT2, TRCK, APIC mp3 = MP3(filename, v2_version=3) try: mp3.add_tags() except: pass mp3.tags['TPE1'] = TPE1(encoding=3, text=songinfo['singers']) mp3.tags['TALB'] = TALB(encoding=3, text=songinfo['album']) mp3.tags['TIT2'] = TIT2(encoding=3, text=songinfo['songname']) mp3.tags['TRCK'] = TRCK(encoding=3, text=str(songinfo['track'])) mp3.tags.add(APIC( encoding=3, mime='image/jpeg', type=3, desc='Cover', data=open(cover_file, 'rb').read() )) mp3.save(v2_version=3) if filename.endswith('m4a'): checkDir(os.path.join(songinfo['savedir'], 'output')) os.system("ffmpeg -i \"%s\" -i \"%s\" -map 0:0 -map 1:0 -metadata album=\"%s\" -metadata artist=\"%s\" -metadata title=\"%s\" -metadata track=\"%d/%d\" \"%s\"" %\ (filename, cover_file, songinfo['album'], songinfo['singers'], songinfo['songname'], songinfo['track'], songinfo['total'], os.path.join(songinfo['savedir'], 'output', songinfo['savename']+'.mp3'))) except Exception as e: print(e) is_success = False return is_success
def add_metadata(mp3_dir, mp3_file_name, video_id): """ Adds metadata to an mp3 file :param mp3_dir: Directory of the mp3 file (Including filename) :param mp3_file_name: Just the filename of the mp3 file :param video_id: Youtube video id mp3 was extracted from """ metadata = get_metadata_obj(mp3_file_name, video_id) audio = MP3(mp3_dir, ID3=ID3) try: audio.add_tags() except: # Presumably would happen if the mp3 # already had tags, but that shouldn't # be possible with our setup pass audio.tags.add( APIC(encoding=3, mime="image/jpeg", type=3, desc="Thumbnail", data=open(metadata["thumbnail"], "rb").read())) audio.tags.add(TIT2(encoding=3, text=metadata["title"])) audio.tags.add(TALB(encoding=3, text=metadata["album"])) audio.tags.add(TPE1(encoding=3, text=metadata["artist"])) audio.save()
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 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 run(self): audio = MP3(mp3Arquivo) capaMp3 = '' if not capaArquivo: try: capaMp3 = audio.tags['APIC:'].data except: pass audio.delete() audio["TIT2"] = TIT2(encoding=3, text=unicode(strTitulo)) audio["TALB"] = TALB(encoding=3, text=unicode(strAlbum)) audio["TPE1"] = TPE1(encoding=3, text=unicode(strBanda)) audio["TDRC"] = TDRC(encoding=3, text=unicode(strAno)) audio["TRCK"] = TRCK(encoding=3, text=unicode(strTrack + '/' + strTotal)) audio["TPOS"] = TPOS(encoding=3, text=unicode(strNumAlbum + '/' + strTotalAlbum)) if capaArquivo or capaMp3: imagedata = capaArquivo or capaMp3 audio["APIC"] = APIC(encoding=3, mime='image/jpg', type=3, desc='', data=imagedata) audio.save() print 'Arquivo finalizado: ', self.mp3Arquivo
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 get_song(song): print("Downloading Music(%s)..." % song['title']) filename = song['sha256'] + '.mp3' download(filename, song['url']) print("Downloading meta-data...") download('tmp.jpg', song['picture']) audio = MP3(filename, ID3=ID3) try: audio.add_tags() except error: pass 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=u'Cover', data=open('tmp.jpg', mode='rb').read())) audio.tags.add(TIT2(encoding=3, text=song['title'])) audio.tags.add(TALB(encoding=3, text=song['albumtitle'])) audio.tags.add(TPE1(encoding=3, text=song['artist'])) audio.tags.add(TDRC(encoding=3, text=song['public_time'])) audio.save()