def _audio_tpos(atuple): audio, atag, advanced, _, _ = atuple if advanced: param = ast.literal_eval(atag) audio.add(TPOS(3, param[1])) else: audio.add(TPOS(3, atag))
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 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 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 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 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 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 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 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(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 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 tag(self, flac_filename, mp3_filename): flac = FLAC(flac_filename) id3 = ID3() involved_people = [] for tag, value in flac.iteritems(): if tag in self.tag_map: id3.add(self.tag_map[tag](encoding=3, text=value)) elif tag in self.text_tag_map: id3.add( TXXX(encoding=3, desc=self.text_tag_map[tag], text=value)) elif tag == 'tracknumber': value[0] += self._total(flac, ['tracktotal', 'totaltracks']) id3.add(TRCK(encoding=3, text=value)) elif tag == 'discnumber': value[0] += self._total(flac, ['disctotal', 'totaldiscs']) id3.add(TPOS(encoding=3, text=value)) elif tag == 'musicbrainz_trackid': id3.add(UFID(u'http://musicbrainz.org', value[0])) elif tag in ('producer', 'engineer', 'arranger'): involved_people.extend((unicode(tag), v) for v in value) elif tag == 'mixer': involved_people.extend((u'mix', v) for v in value) elif tag == 'performer': id3.add(TMCL(encoding=3, people=self._performers(value))) elif tag not in [ 'tracktotal', 'totaltracks', 'disctotal', 'totaldiscs', 'replaygain_album_gain', 'replaygain_album_peak', 'replaygain_track_gain', 'replaygain_track_peak', # Don't know what to do with reference loudness - ignore it 'replaygain_reference_loudness', # No mapping for mp3 - https://picard.musicbrainz.org/docs/mappings/ 'originalyear', # Drop CDDB disc id 'discid' ]: raise UnknownTag("%s=%s" % (tag, value)) if involved_people: id3.add(TIPL(encoding=3, people=involved_people)) self._replaygain(flac, id3, 'album') self._replaygain(flac, id3, 'track') for pic in flac.pictures: tag = APIC(encoding=3, mime=pic.mime, type=pic.type, desc=pic.desc, data=pic.data) id3.add(tag) id3.save(mp3_filename)
def setStuff(filename, title=None, artist=None, albumArtist=None, album=None, track=None, totalTracks=None, year=None, genre=None, artwork=False, write=False, clean=False): try: audio = MP3(filename) except: print(" - Failed.") return False if clean: # Delete all tags audio.clear() audio["TPOS"] = TPOS(encoding=3, text=u"1/1") if title is not None: audio["TIT2"] = TIT2(encoding=3, text=title) if artist is not None: audio["TPE1"] = TPE1(encoding=3, text=artist) if albumArtist is None: audio["TPE2"] = TPE2(encoding=3, text=artist) if albumArtist is not None: audio["TPE2"] = TPE2(encoding=3, text=albumArtist) if artist is None: audio["TPE1"] = TPE1(encoding=3, text=albumArtist) if album is not None: audio["TALB"] = TALB(encoding=3, text=album) if track is not None: audio["TRCK"] = TRCK(encoding=3, text="%d" % int(track)) if year is not None: audio["TDRC"] = TDRC(encoding=3, text=str(year)) if genre is not None: audio["TCON"] = TCON(encoding=3, text=genre) if artwork: # Add 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=u'', data=artwork ) ) if write: audio.save() print(" - Done.") else: print("") return audio
def CopyTags(source_file, target_file): o = OggVorbis(source_file) m = EasyID3(target_file) for key in ['artist', 'title', 'album', 'date', 'genre', 'tracknumber']: if o.has_key(key): m[key] = o[key] m.save() if o.has_key('discnumber'): m = MP3(target_file) m['TPOS'] = TPOS(encoding=3, text=o['discnumber']) m.save()
def setmp3tag(mp3file, image=None, title=None, album=None, artist=None, track_num=None, year=None, genre=None, total_track_num=None, disc_num=None, total_disc_num=None): audio = MP3(mp3file, ID3=ID3) try: audio.add_tag() except Exception: pass if image is not None: with open(image, 'rb') as f: audio.tags.add(APIC( encoding=3, mime='image/jpeg', type=3, desc='Cover Picture', data=f.read())) if title is not None: audio.tags.add(TIT2(encoding=3, text=title)) if album is not None: audio.tags.add(TALB(encoding=3, text=album)) if artist is not None: audio.tags.add(TPE1(encoding=3, text=artist)) audio.tags.add(TPE2(encoding=3, text=artist)) if track_num is not None: if total_track_num is None: audio.tags.add(TRCK(encoding=3, text=str(track_num))) else: audio.tags.add(TRCK(encoding=3, text='{}/{}'.format(track_num, total_track_num))) if disc_num is not None: if total_disc_num is None: audio.tags.add(TPOS(encoding=3, text=str(disc_num))) else: audio.tags.add(TPOS(encoding=3, text='{}/{}'.format(disc_num, total_disc_num))) if genre is not None: audio.tags.add(TCON(encoding=3, text=genre)) if year is not None: audio.tags.add(TYER(encoding=3, text=str(year))) audio.save(v2_version=3, v1=2)
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 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'])) id3.save(file_name)
def add_metadata(self, filename, song): """ http://id3.org/id3v2.4.0-frames """ log.info('adding metadata') log.info(self.folder_path) if os.path.isfile(self.folder_path + "/" + filename + ".mp3"): mp3file = MP3(filename + ".mp3", ID3=ID3) if self.kwargs["metadata"]: opts = [int(o) for o in bin(self.kwargs["metadata"])[2:]] else: opts = [1, 1, 1 ] if self.sp_tracklist.type == "album" else [1, 1, 0] if opts[0]: #default mp3file['TIT2'] = TIT2(encoding=3, text=song.title) mp3file['TPE1'] = TPE1(encoding=3, text=song.artist) if opts[1]: #default mp3file['TALB'] = TALB(encoding=3, text=song.album) cover = requests.get(song.cover[1]).content if cover: mp3file['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=cover) else: log.warning("Error while getting cover") if opts[2]: #default for album download mp3file['TPE2'] = TPE2(encoding=3, text=song.album_artist) mp3file['TPOS'] = TPOS(encoding=3, text=str(song.disc_num)) mp3file['TRCK'] = TRCK(encoding=3, text=str(song.track_num)) #mp3file['TIT3'] = TIT3(encoding=3, text="Subtitle") #mp3file['COMM'] = COMM(encoding=3, text="Comment") #add comment with youtube and spotify url? mp3file.save() else: log.info("skipped song")
def setID3(self, path, res=480): 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.getCoverArt(res) tags.add( APIC(encoding=3, mime='image/jpg', type=3, desc=u'Cover', data=open(img_path, 'rb').read())) tags.save()
def CopyTagsToTranscodedFileMp3(losslessFile, lossyFile): # Because the input flac file is decoded to wav, all metadata is lost. We have to extract this metadata from # the flac file and put it directly into the generated mp3 file. from mutagen.flac import FLAC from mutagen.id3 import ID3 flacFile = FLAC(losslessFile) flacFileTags = flacFile.tags mp3File = ID3(lossyFile) mp3File.delete() for key,value in flacFileTags.items(): if key == 'title': from mutagen.id3 import TIT2 mp3File.add(TIT2(encoding=3, text=value)) elif key == 'album': from mutagen.id3 import TALB mp3File.add(TALB(encoding=3, text=value)) elif key == 'artist': from mutagen.id3 import TPE1 mp3File.add(TPE1(encoding=3, text=value)) elif key == 'tracknumber': from mutagen.id3 import TRCK mp3File.add(TRCK(encoding=3, text=value)) elif key == 'date': from mutagen.id3 import TDRC mp3File.add(TDRC(encoding=3, text=value)) elif key == 'genre': from mutagen.id3 import TCON mp3File.add(TCON(encoding=3, text=value)) elif key == 'discnumber': from mutagen.id3 import TPOS mp3File.add(TPOS(encoding=3, text=value)) elif key == 'composer': from mutagen.id3 import TCOM mp3File.add(TCOM(encoding=3, text=value)) elif key == 'conductor': from mutagen.id3 import TPE3 mp3File.add(TPE3(encoding=3, text=value)) elif key == 'ensemble': from mutagen.id3 import TPE2 mp3File.add(TPE2(encoding=3, text=value)) elif key == 'comment': from mutagen.id3 import COMM mp3File.add(COMM(encoding=3, text=value)) elif key == 'publisher': from mutagen.id3 import TPUB mp3File.add(TPUB(encoding=3, text=value)) elif key == 'opus': from mutagen.id3 import TIT3 mp3File.add(TIT3(encoding=3, text=value)) elif key == 'sourcemedia': from mutagen.id3 import TMED mp3File.add(TMED(encoding=3, text=value)) elif key == 'isrc': from mutagen.id3 import TSRC mp3File.add(TSRC(encoding=3, text=value)) elif key == 'license': from mutagen.id3 import TOWN mp3File.add(TOWN(encoding=3, text=value)) elif key == 'copyright': from mutagen.id3 import WCOP mp3File.add(WCOP(encoding=3, text=value)) elif key == 'encoded-by': from mutagen.id3 import TENC mp3File.add(TENC(encoding=3, text=value)) elif (key == 'part' or key == 'partnumber'): from mutagen.id3 import TIT3 mp3File.add(TIT3(encoding=3, text=value)) elif (key == 'lyricist' or key == 'textwriter'): from mutagen.id3 import TIT3 mp3File.add(TIT3(encoding=3, text=value)) else: from mutagen.id3 import TXXX mp3File.add(TXXX(encoding=3, text=value, desc=key)) mp3File.update_to_v24() mp3File.save() return
def save_mp3_metadata(self, file_path, data): """ Saves the given metadata for an MP3 file. Metadata.save_mp3_metadata(str, dict) """ audio = ID3(file_path) # Writing MP3 tags needs ID3 mp3_audio, format = self.get_mutagen_parser(file_path) if data.get("title"): audio.add(TIT2(encoding=3, text=unicode(data['title']))) if data.get("artist"): audio.add(TPE1(encoding=3, text=unicode(data['artist']))) if data.get("album"): audio.add(TALB(encoding=3, text=unicode(data['album']))) if data.get("genre"): audio.add(TCON(encoding=3, text=unicode(data['genre']))) if data.get("year"): audio.add(TDRC(encoding=3, text=unicode(data['year']))) if data.get("album_artist"): audio.add(TPE2(encoding=3, text=unicode(data['album_artist']))) if data.get("track_number", False) and data.get("total_tracks", False): audio.add( TRCK(encoding=3, text=unicode(data['track_number'] + '/' + data['total_tracks']))) elif data.get("track_number"): total_tracks = self.get_total_tracks(mp3_audio, format) if total_tracks == None: audio.add(TRCK(encoding=3, text=unicode(data['track_number']))) else: audio.add( TRCK(encoding=3, text=unicode(data['track_number'] + '/' + total_tracks))) elif data.get("total_tracks"): t_no = self.get_track_number(mp3_audio, format) if t_no == None: audio.add( TRCK(encoding=3, text=unicode(" /" + data["total_tracks"]))) else: audio.add( TRCK(encoding=3, text=unicode(t_no + '/' + data["total_tracks"]))) if data.get("disc_number", False) and data.get("total_discs", False): audio.add( TPOS(encoding=3, text=unicode(data['disc_number'] + '/' + data['total_discs']))) elif data.get("disc_number"): total_discs = self.get_total_discs(mp3_audio, format) if total_discs == None: audio.add(TPOS(encoding=3, text=unicode(data['disc_number']))) else: audio.add( TPOS(encoding=3, text=unicode(data['disc_number'] + '/' + total_discs))) elif data.get("total_discs"): d_no = self.get_disc_number(mp3_audio, format) if d_no == None: audio.add( TPOS(encoding=3, text=unicode(" /" + data["total_discs"]))) else: audio.add( TPOS(encoding=3, text=unicode(d_no + '/' + data["total_discs"]))) if data.get("composer"): audio.add(TCOM(encoding=3, text=unicode(data['composer']))) if data.get("publisher"): audio.add(TPUB(encoding=3, text=unicode(data['publisher']))) if data.get("comments"): audio.add( COMM(encoding=3, lang="eng", desc="", text=unicode(data['comments']))) audio.save()
def disc_number(self, disc: str): self.file['TPOS'] = TPOS(encoding=3, text=disc) return self
lambda amsong: TCON(text=amsong.genres[0]), "album_artist": lambda amsong: TPE2(text=amsong.album.artist_name), "song_artist": lambda amsong: TPE1(text=amsong.artist_name), "itunes_advisory": lambda amsong: TXXX(desc="ITUNESADVISORY", text="1") if amsong.is_explicit else None, "release_date": lambda amsong: TDRC(text=amsong.release_date), "artwork": lambda amsong: APIC(mime='image/jpeg', desc='cover', data=amsong.get_artwork(prefer_album=True)), "disc_position": lambda amsong: TPOS(text=amsong.disc_number) if '/' in str(amsong.disc_number) else None, "track_position": lambda amsong: TRCK(text= f"{amsong.track_number}/{amsong.album.track_count}") } ERROR_MSG = "--> For '{song}' failed tagging: {tags}" class Tagger: """ A class for handling songs metadata. """ def __init__(self, path): self.path = realpath(path)
aux = musica.split(' ', 1)[1] strTitulo = aux.split('.mp3')[0] print strTrack + '/' + strTotal + ' - ' + strNumAlbum + '/' + strTotalAlbum + ' - ' + strTitulo audio = MP3(diretorio+banda+'/'+album+'/'+musica) # Se não tem o arquivo capa.jpg, tenta ler a capa do arquivo capaMp3 = '' if not capaArquivo: try: capaMp3 = audio.tags['APIC:'].data except: pass if capaMp3: fcapa = open(diretorio+banda+'/'+album+'/capa.jpg', 'wb') fcapa.write(capaMp3) fcapa.close 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()
episodeNum = d.entries[0].itunes_episode seasonNum = d.entries[0].itunes_season fileName = title + ".mp3" urllib.request.urlretrieve(url,fileName) try: audio = ID3(fileName) audio.delete() audio = ID3() except ID3NoHeaderError: print("Adding ID3 header") audio = ID3() audio.add(TIT2(encoding=3,text=title)) #add title audio.add(TRCK(encoding=3,text=episodeNum)) #add track number audio.add(TPOS(encoding=3,text=seasonNum)) #add season number audio.add(TPE1(encoding=3,text=podcast['artist'])) #add artist audio.add(TPE2(encoding=3,text=podcast['album_artist'])) #add album artist audio.add(TALB(encoding=3,text=podcast['album'])) #add album audio.save(fileName) #this save function only saves the ID3 tags, it does not resave the mp3. So, if you don't have it pointed at the actual file location it will just save a text file full of metadata that will be useless elif podcast['host'] == 'art19': url = d.entries[0].links[0].href title = d.entries[0].title.rstrip() episodeNum = d.entries[0].itunes_episode seasonNum = d.entries[0].itunes_season fileName = title + ".mp3" urllib.request.urlretrieve(url,fileName) try: audio = ID3(fileName) audio.delete()
def copyTagsToTranscodedFileMp3(losslessFile, lossyFile): # # Copy the tags from the losslessFile (.flac) to the lossyFile. # All previous tags from the lossyFile will be deleted before the # tags from the losslessFile are copied. # from mutagen.flac import FLAC from mutagen.id3 import ID3 # Read all tags from the flac file flacFile = FLAC(losslessFile) flacFileTags = flacFile.tags # Returns a dictionary containing the flac tags # Only mp3 files with ID3 headers can be openend. # So be sure to add some tags during encoding .wav. to mp3 # Mapping from Vorbis comments field recommendations to id3v2_4_0 # For more information about vorbis field recommendations: http://reactor-core.org/ogg-tagging.html # For more information about id3v2_4_0 frames: http://www.id3.org/id3v2.4.0-frames # # Single value tags: # ALBUM -> TALB # ARTIST -> TPE1 # PUBLISHER -> TPUB # COPYRIGHT -> WCOP # DISCNUMBER -> TPOS # ISRC -> TSRC # EAN/UPN # LABEL # LABELNO # LICENSE -> TOWN # OPUS -> TIT3 # SOURCEMEDIA -> TMED # TITLE -> TIT2 # TRACKNUMBER -> TRCK # VERSION # ENCODED-BY -> TENC # ENCODING # Multiple value tags: # COMPOSER -> TCOM # ARRANGER # LYRICIST -> TEXT # AUTHOR -> TEXT # CONDUCTOR -> TPE3 # PERFORMER -> # ENSEMBLE -> TPE2 # PART -> TIT1 # PARTNUMBER -> TIT1 # GENRE -> TCON # DATE -> TDRC # LOCATION # COMMENT -> COMM # Other vorbis tags are mapped to TXXX tags mp3File = ID3(lossyFile) mp3File.delete() for key, value in flacFileTags.items(): if key == 'title': # Map to TIT2 frame from mutagen.id3 import TIT2 mp3File.add(TIT2(encoding=3, text=value)) elif key == 'album': # Map to TALB frame from mutagen.id3 import TALB mp3File.add(TALB(encoding=3, text=value)) elif key == 'artist': # Map to TPE1 frame from mutagen.id3 import TPE1 mp3File.add(TPE1(encoding=3, text=value)) elif key == 'tracknumber': # Map to TRCK frame from mutagen.id3 import TRCK mp3File.add(TRCK(encoding=3, text=value)) elif key == 'date': # Map to TDRC frame from mutagen.id3 import TDRC mp3File.add(TDRC(encoding=3, text=value)) elif key == 'genre': # Map to TCON frame from mutagen.id3 import TCON mp3File.add(TCON(encoding=3, text=value)) elif key == 'discnumber': # Map to TPOS frame from mutagen.id3 import TPOS mp3File.add(TPOS(encoding=3, text=value)) elif key == 'composer': # Map to TCOM frame from mutagen.id3 import TCOM mp3File.add(TCOM(encoding=3, text=value)) elif key == 'conductor': # Map to TPE3 frame from mutagen.id3 import TPE3 mp3File.add(TPE3(encoding=3, text=value)) elif key == 'ensemble': # Map to TPE2 frame from mutagen.id3 import TPE2 mp3File.add(TPE2(encoding=3, text=value)) elif key == 'comment': # Map to COMM frame from mutagen.id3 import COMM mp3File.add(COMM(encoding=3, text=value)) elif key == 'publisher': # Map to TPUB frame from mutagen.id3 import TPUB mp3File.add(TPUB(encoding=3, text=value)) elif key == 'opus': # Map to TIT3 frame from mutagen.id3 import TIT3 mp3File.add(TIT3(encoding=3, text=value)) elif key == 'sourcemedia': # Map to TMED frame from mutagen.id3 import TMED mp3File.add(TMED(encoding=3, text=value)) elif key == 'isrc': # Map to TSRC frame from mutagen.id3 import TSRC mp3File.add(TSRC(encoding=3, text=value)) elif key == 'license': # Map to TOWN frame from mutagen.id3 import TOWN mp3File.add(TOWN(encoding=3, text=value)) elif key == 'copyright': # Map to WCOP frame from mutagen.id3 import WCOP mp3File.add(WCOP(encoding=3, text=value)) elif key == 'encoded-by': # Map to TENC frame from mutagen.id3 import TENC mp3File.add(TENC(encoding=3, text=value)) elif (key == 'part' or key == 'partnumber'): # Map to TIT3 frame from mutagen.id3 import TIT3 mp3File.add(TIT3(encoding=3, text=value)) elif (key == 'lyricist' or key == 'textwriter'): # Map to TEXT frame from mutagen.id3 import TIT3 mp3File.add(TIT3(encoding=3, text=value)) else: #all other tags are mapped to TXXX frames # Map to TXXX frame from mutagen.id3 import TXXX mp3File.add(TXXX(encoding=3, text=value, desc=key)) mp3File.update_to_v24() mp3File.save() return
def __init_id3_tags(id3, major=3): """ Attributes: id3 ID3 Tag object major ID3 major version, e.g.: 3 for ID3v2.3 """ from mutagen.id3 import TRCK, TPOS, TXXX, TPUB, TALB, UFID, TPE2, \ TSO2, TMED, TIT2, TPE1, TSRC, IPLS, TORY, TDAT, TYER id3.add(TRCK(encoding=major, text="1/10")) id3.add(TPOS(encoding=major, text="1/1")) id3.add( TXXX(encoding=major, desc="MusicBrainz Release Group Id", text="e00305af-1c72-469b-9a7c-6dc665ca9adc")) id3.add(TXXX(encoding=major, desc="originalyear", text="2011")) id3.add( TXXX(encoding=major, desc="MusicBrainz Album Type", text="album")) id3.add( TXXX(encoding=major, desc="MusicBrainz Album Id", text="e7050302-74e6-42e4-aba0-09efd5d431d8")) id3.add(TPUB(encoding=major, text="J&R Adventures")) id3.add(TXXX(encoding=major, desc="CATALOGNUMBER", text="PRAR931391")) id3.add(TALB(encoding=major, text="Don\'t Explain")) id3.add( TXXX(encoding=major, desc="MusicBrainz Album Status", text="official")) id3.add(TXXX(encoding=major, desc="SCRIPT", text="Latn")) id3.add( TXXX(encoding=major, desc="MusicBrainz Album Release Country", text="US")) id3.add(TXXX(encoding=major, desc="BARCODE", text="804879313915")) id3.add( TXXX(encoding=major, desc="MusicBrainz Album Artist Id", text=[ "3fe817fc-966e-4ece-b00a-76be43e7e73c", "984f8239-8fe1-4683-9c54-10ffb14439e9" ])) id3.add(TPE2(encoding=major, text="Beth Hart & Joe Bonamassa")) id3.add(TSO2(encoding=major, text="Hart, Beth & Bonamassa, Joe")) id3.add(TXXX(encoding=major, desc="ASIN", text="B005NPEUB2")) id3.add(TMED(encoding=major, text="CD")) id3.add( UFID(encoding=major, owner="http://musicbrainz.org", data=b"f151cb94-c909-46a8-ad99-fb77391abfb8")) id3.add(TIT2(encoding=major, text="Sinner's Prayer")) id3.add( TXXX(encoding=major, desc="MusicBrainz Artist Id", text=[ "3fe817fc-966e-4ece-b00a-76be43e7e73c", "984f8239-8fe1-4683-9c54-10ffb14439e9" ])) id3.add(TPE1(encoding=major, text=["Beth Hart & Joe Bonamassa"])) id3.add( TXXX(encoding=major, desc="Artists", text=["Beth Hart", "Joe Bonamassa"])) id3.add(TSRC(encoding=major, text=["NLB931100460", "USMH51100098"])) id3.add( TXXX(encoding=major, desc="MusicBrainz Release Track Id", text="d062f484-253c-374b-85f7-89aab45551c7")) id3.add( IPLS(encoding=major, people=[["engineer", "James McCullagh"], ["engineer", "Jared Kvitka"], ["arranger", "Jeff Bova"], ["producer", "Roy Weisman"], ["piano", "Beth Hart"], ["guitar", "Blondie Chaplin"], ["guitar", "Joe Bonamassa"], ["percussion", "Anton Fig"], ["drums", "Anton Fig"], ["keyboard", "Arlan Schierbaum"], ["bass guitar", "Carmine Rojas"], ["orchestra", "The Bovaland Orchestra"], ["vocals", "Beth Hart"], ["vocals", "Joe Bonamassa"]])), id3.add(TORY(encoding=major, text="2011")) id3.add(TYER(encoding=major, text="2011")) id3.add(TDAT(encoding=major, text="2709"))