def test_make_v1_from_tyer(self): self.assertEquals( MakeID3v1({"TDRC": TDRC(text="2010-10-10")}), MakeID3v1({"TYER": TYER(text="2010")})) self.assertEquals( ParseID3v1(MakeID3v1({"TDRC": TDRC(text="2010-10-10")})), ParseID3v1(MakeID3v1({"TYER": TYER(text="2010")})))
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 _audio_tdrc(atuple): audio, atag, advanced, _, _ = atuple if advanced: param = ast.literal_eval(atag) audio.add(TDRC(3, param[1])) else: audio.add(TDRC(3, atag))
def test_save_v23_recurse_restore(self): self.realid3.add(CHAP(sub_frames=[TDRC(text="2006")])) self.realid3.add(CTOC(sub_frames=[TDRC(text="2006")])) self.id3.save(self.filename, v2_version=3) for frame_id in ["CHAP", "CTOC"]: chap = self.realid3.getall(frame_id)[0] assert chap.sub_frames.getall("TDRC")[0] == "2006" new = ID3(self.filename, translate=False) assert new.version == (2, 3, 0) chap = new.getall(frame_id)[0] assert not chap.sub_frames.getall("TDRC") assert chap.sub_frames.getall("TYER")[0] == "2006"
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 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 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()
def tag_resulting_track(out_file_path, track_info): try: track_to_tag = ID3(out_file_path) except mutagen.id3.error: track_to_tag = ID3() track_to_tag.save(out_file_path) track_to_tag.add(TPE1(encoding=3, text=track_info['track_artist'])) # Artist track_to_tag.add(TIT2(encoding=3, text=track_info['track_title'])) # Title track_to_tag.add(TSRC(encoding=3, text=track_info['ISRC'])) # ISRC track_to_tag.add(TRCK(encoding=3, text=track_info['track_number'])) # Track Number track_to_tag.add(TPOS(encoding=3, text=track_info['disc_number'])) # Disc Number track_to_tag.add(TALB(encoding=3, text=track_info['album_title'])) # Album Title track_to_tag.add(TDRC(encoding=3, text=track_info['album_year'])) # Year track_to_tag.add(TPUB(encoding=3, text=track_info['label'])) # Label track_to_tag.add(TPE2(encoding=3, text=track_info['album_artist'])) # Album artist track_to_tag.add(TCON(encoding=3, text=track_info['genre'])) # Genre track_to_tag.save(out_file_path)
def write_id3_tags(sermon): if sermon.sermon.name == "": return fname = sermon.sermon.file.name UTF8 = 3 # mutagen.id3 says so. try: tags = ID3(fname) except Exception: # Could be missing or malformed header tags = ID3() tags.filename = fname tags.add(TIT2(encoding=UTF8, text=sermon.title)) tags.add( TDRC(encoding=UTF8, text=sermon.date_delivered.strftime('%Y-%m-%d') + ' ' + sermon.time_delivered.strftime('%H:%M'))) tags.add(TPE1(encoding=UTF8, text=sermon.speaker.name)) topics = sermon.topics.all() comment = (""" Sermon: Speaker: %(speaker)s Bible book: %(bible_book)s Text: %(passage)s Series: %(series)s Topics: %(topics)s """ % dict(speaker=sermon.speaker.name, bible_book=sermon.bible_book, passage=sermon.passage, series=sermon.series.name if sermon.series is not None else '', topics=', '.join(t.name for t in topics) if topics else '')) tags.add(COMM(encoding=UTF8, lang='eng', text=comment)) tags.save()
def encodeMP3(self, wavf, dstf, cover, meta): FNULL = open(os.devnull, 'w') subprocess.call(['lame', '-V2', wavf, dstf], stdout=FNULL, stderr=FNULL) FNULL.close() # tag MP3 mm = TrackMeta(meta) mp3 = MP3(dstf, ID3=ID3) mp3["TIT2"] = TIT2(encoding=3, text=mm.title()) mp3["TPE1"] = TPE1(encoding=3, text=mm.artist()) mp3["TALB"] = TALB(encoding=3, text=mm.album()) mp3["TPE2"] = TPE2(encoding=3, text=mm.albumartist()) if mm.date(): mp3["TDRC"] = TDRC(encoding=3, text=mm.date()) mp3["TRCK"] = TRCK(encoding=3, text=mm.tracknumber()+"/"+mm.tracktotal()) mp3["TPOS"] = TPOS(encoding=3, text=mm.discnumber()+"/"+mm.disctotal()) # composer if mm.composer(): mp3["TCM"] = TCM(encoding=3, text=mm.composer()) # cover if cover: data = open(cover, 'rb').read() covr = [] if cover.endswith('png'): mime = 'image/png' else: mime = 'image/jpeg' mp3.tags.add(APIC(encoding=3, mime=mime, type=3, desc=u'Cover', data=data)) # save mp3.save()
def ok_pressed(): try: tags = ID3(_dir + "/" + __dir) except: print("Adding ID3 header;") tags = ID3() tags['TRCK'] = TRCK(encoding=3, text=edit_entry_list[TRACK_ID].get()) tags['TIT2'] = TIT2(encoding=3, text=edit_entry_list[TITLE_ID].get()) tags['TPE1'] = TPE1(encoding=3, text=edit_entry_list[ARTIST_ID].get()) tags['TALB'] = TALB(encoding=3, text=edit_entry_list[ALBUM_ID].get()) tags['TDRC'] = TDRC(encoding=3, text=edit_entry_list[YEAR_ID].get()) tags['TCOM'] = TCOM(encoding=3, text=edit_entry_list[COMPOSER_ID].get()) tags['TEXT'] = TEXT(encoding=3, text=edit_entry_list[LYRICIST_ID].get()) tags['TXXX:PERFORMER'] = TXXX(encoding=3, desc='PERFORMER', text=edit_entry_list[PERFORMER_ID].get()) try: tags.save(_dir + "/" + __dir) except: print("denied") new_val = list(tree.item(right_row)['values']) for in_id in edit_id: if new_val[in_id] != edit_entry_list[in_id].get(): new_val[in_id] = edit_entry_list[in_id].get() tree.item(right_row, values=new_val) win.destroy()
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 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 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 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 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 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 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 _fix_song_tags(cls, tracks: Iterable[SongFile], dry_run: bool = False, add_bpm: bool = False, callback: Callable = None): prefix, add_msg, rmv_msg = ('[DRY RUN] ', 'Would add', 'remove') if dry_run else ('', 'Adding', 'removing') for n, music_file in enumerate(tracks, 1): if callback: callback(music_file, n) music_file.cleanup_lyrics(dry_run) tag_type = music_file.tag_type if tag_type != 'id3': log.debug(f'Skipping tag fix for non-MP3: {music_file}') continue elif not isinstance((track_tags := music_file.tags), ID3): log.debug( f'Skipping tag fix due to no tags present in {music_file}') continue tdrc = track_tags.getall('TDRC') txxx_date = track_tags.getall('TXXX:DATE') if (not tdrc) and txxx_date: file_date = txxx_date[0].text[0] log.info( f'{prefix}{add_msg} TDRC={file_date} to {music_file} and {rmv_msg} its TXXX:DATE tag' ) if not dry_run: track_tags.add(TDRC(text=file_date)) track_tags.delall('TXXX:DATE') music_file.save()
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 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 tagFile(self, filename, metadata, art_url): image = None if art_url is not None: self.getFile('artwork.jpg', art_url, True) try: with open('artwork.jpg', 'rb') as file: image = file.read() except: pass if filename.endswith('.mp3'): audio = MP3(filename, ID3=ID3) try: audio.add_tags() except: pass audio.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=image)) audio.tags["TIT2"] = TIT2(encoding=3, text=metadata['title']) audio.tags["TPE1"] = TPE1(encoding=3, text=metadata['artist']) audio.tags["TDRC"] = TDRC(encoding=3, text=unicode(metadata['year'])) audio.tags["TCON"] = TCON(encoding=3, text=metadata['genre']) audio.save() elif filename.endswith('.flac'): audio = FLAC(filename) try: audio.add_tags() except: pass audio.tags['title'] = metadata['title'] audio.tags['artist'] = metadata['artist'] audio.tags['year'] = metadata['year'] audio.tags['genre'] = metadata['genre'] audio.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=image)) audio.save() elif filename.endswith('.m4a'): audio = MP4(filename) try: audio.add_tags() except: pass covr = [] covr.append(MP4Cover(image, MP4Cover.FORMAT_JPEG)) audio.tags['covr'] = covr audio.tags['title'] = metadata['title'] audio.tags['artist'] = metadata['artist'] #audio.tags['year'] = metadata['year'] audio.tags['genre'] = metadata['genre'] audio.save() if os.path.isfile('artwork.jpg'): os.remove('artwork.jpg')
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 _add_metadata(self, show, file_name): if file_name is None: raise "file_name is not set - you cannot add metadata to None" config = Configuration() time_string = format_date(config.date_pattern, time.localtime(self.start_time)) comment = config.comment_pattern % { 'show': show.name, 'date': time_string, 'year': time.strftime('%Y', time.gmtime()), 'station': show.station.name, 'link_url': show.get_link_url() } audio = ID3() # See http://www.id3.org/id3v2.3.0 for details about the ID3 tags audio.add(TIT2(encoding=2, text=["%s, %s" % (show.name, time_string)])) audio.add( TDRC(encoding=2, text=[format_date('%Y-%m-%d %H:%M', self.start_time)])) audio.add(TCON(encoding=2, text=[u'Podcast'])) audio.add(TALB(encoding=2, text=[show.name])) audio.add(TLEN(encoding=2, text=[show.duration * 1000])) audio.add(TPE1(encoding=2, text=[show.station.name])) audio.add(TCOP(encoding=2, text=[show.station.name])) audio.add(COMM(encoding=2, lang='eng', desc='desc', text=comment)) audio.add(TCOM(encoding=2, text=[show.get_link_url()])) self._add_logo(show, audio) audio.save(file_name)
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 modifyTags(songpath, pic, singername, songname, albumname, isalbum=False, albumdate='', belongcd='', cdidx=1, dicsnum=1): coverpath = "%s/%s - cover.jpg" % (musicpath, albumname) img = None if isalbum and os.path.exists(coverpath): img = open(coverpath, "rb") else: request = urllib.request.Request(pic) request.add_header( 'User-agent', 'Mozilla/5.0 (Macintosh; Intel) Gecko/20100101 Firefox/63.0') request.add_header('Cache-Control', 'max-age=0, no-cache') request.add_header('Host', 'y.qq.com') request.add_header('Referer', 'https://y.qq.com/n/yqq/toplist/4.html') img = urllib.request.urlopen(request) meta = None try: meta = mutagen.File(songpath) except (FileNotFoundError, mutagen.MutagenError): print('mutagen.MutagenError: ' '%s' '' % songpath) return try: meta.add_tags() except mutagen.MutagenError: None meta['TIT2'] = TIT2( # 插入歌名 encoding=1, text=[songname]) meta['TPE1'] = TPE1( # 插入第一演奏家、歌手、等 encoding=1, text=[singername]) meta['TALB'] = TALB( # 插入专辑 encoding=1, text=[albumname]) meta['APIC'] = APIC( # 插入图片 encoding=1, mime='image/jpeg', type=3, desc=u'Cover', data=img.read()) # write addition mp3 tag if isalbum: meta['TDRC'] = TDRC( # 插入专辑年份 encoding=1, text=[albumdate]) meta['TRCK'] = TRCK( # 插入曲目编号 encoding=1, text=[belongcd]) if dicsnum != 1: meta['TPOS'] = TPOS( # 碟片编号 encoding=1, text=['%02d/%d' % (cdidx, dicsnum)]) meta.save()
def parse_tdrc(self, id3, release): if release.get('date', ''): try: date = parse_date(release['date']) except ValueError: return self.pop(id3, 'TDRC') id3.add(TDRC(encoding=3, text=str(date.year)))
def mp3_tag(mp3_dirname, mp3_filename, artist, album, track, tracks, title, year, genre, bpms, compilation): # Delete existing tags try: id3 = ID3(mp3_filename) id3.delete() except ID3NoHeaderError: id3 = ID3() # Artist id3.add(TPE1(encoding=3, text=artist)) # Artistsort id3.add(TSOP(encoding=3, text=artist)) # Band id3.add(TPE2(encoding=3, text=artist)) # Composer id3.add(TCOM(encoding=3, text=artist)) # Album id3.add(TALB(encoding=3, text=album)) # Albumsort id3.add(TSOA(encoding=3, text=album)) # Track id3.add(TRCK(encoding=3, text=tracks)) # Title id3.add(TIT2(encoding=3, text=title)) # Year id3.add(TDRC(encoding=3, text=year)) # Genre id3.add(TCON(encoding=3, text=genre)) # BPMs id3.add(TBPM(encoding=3, text=bpms)) # Compilation if (compilation): id3.add(TCMP(encoding=3, text='1')) else: id3.add(TCMP(encoding=3, text='0')) # Cover image = str(mp3_dirname + '/Cover.jpg') try: imagefile = open(image, 'rb').read() id3.add(APIC(3, 'image/jpeg', 3, 'Cover', imagefile)) except: print("Warning. No Cover.jpg in directory " + mp3_dirname + ".") # Save tags to file id3.save(mp3_filename, v2_version=4, v1=2)
def writeID3(track: t.Track): f = ID3(track.path) f["TIT2"] = TIT2(text=track.data["title"]) f["TPE1"] = TPE1(text=track.data["artist"]) f["TALB"] = TALB(text=track.data["album"]) f["TDRC"] = TDRC(text=track.data["date"]) f["TRCK"] = TRCK(text=track.data["track"]) f["COMM::XXX"] = COMM(text=track.data["comment"]) f.save()