def _audio_tpe2(atuple): audio, atag, advanced, _, _ = atuple if advanced: param = ast.literal_eval(atag) audio.add(TPE2(3, param[1])) else: audio.add(TPE2(3, atag))
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 test_unsynch(self): header = ID3Header() header.version = (2, 4, 0) header._flags = 0x80 badsync = b'\x00\xff\x00ab\x00' self.assertEquals(TPE2._fromData(header, 0, badsync), [u"\xffab"]) header._flags = 0x00 self.assertEquals(TPE2._fromData(header, 0x02, badsync), [u"\xffab"]) tag = TPE2._fromData(header, 0, badsync) self.assertEquals(tag, [u"\xff", u"ab"])
def test_text_duplicate_frame_different_encoding(self): id3 = ID3Tags() frame = TPE2(encoding=Encoding.LATIN1, text=[u"foo"]) id3._add(frame, False) assert id3.getall("TPE2")[0].encoding == Encoding.LATIN1 frame = TPE2(encoding=Encoding.LATIN1, text=[u"bar"]) id3._add(frame, False) assert id3.getall("TPE2")[0].encoding == Encoding.LATIN1 frame = TPE2(encoding=Encoding.UTF8, text=[u"baz\u0400"]) id3._add(frame, False) assert id3.getall("TPE2")[0].encoding == Encoding.UTF8 frames = id3.getall("TPE2") assert len(frames) == 1 assert len(frames[0].text) == 3
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 test_compressibly_large(self): f = ID3(self.filename) self.assert_("TPE2" not in f) f["TPE2"] = TPE2(encoding=0, text="Ab" * 1025) f.save() id3 = ID3(self.filename) self.assertEquals(id3["TPE2"], "Ab" * 1025)
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 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 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 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 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 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 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 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 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 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 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 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 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 newArtistTag(self, music_file, artist_string): ''' Add a new artist tag to the mp3 file. ''' audiofile = ID3(music_file) audiofile.add(TPE2(encoding=3, text=u"%s" % (artist_string))) audiofile.save() self.log.logMsg('debug', "Artist tag added to %s" % (str(music_file)), self.PRINT_DEBUG)
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 get_american_life(epno, directory='/mnt/media/thisamericanlife', extraStuff=None, verify=True): """ Downloads an episode of This American Life into a given directory. The description of which URL the episodes are downloaded from is given in http://www.dirtygreek.org/t/download-this-american-life-episodes. The URL is http://audio.thisamericanlife.org/jomamashouse/ismymamashouse/epno.mp3 Otherwise, the URL is http://www.podtrac.com/pts/redirect.mp3/podcast.thisamericanlife.org/podcast/epno.mp3 """ try: title, year = get_americanlife_info(epno, extraStuff=extraStuff, verify=verify) except ValueError as e: print(e) print( 'Cannot find date and title for This American Life episode #%d.' % epno) return if not os.path.isdir(directory): raise ValueError("Error, %s is not a directory." % directory) outfile = os.path.join(directory, 'PRI.ThisAmericanLife.%03d.mp3' % epno) urlopn = 'http://www.podtrac.com/pts/redirect.mp3/podcast.thisamericanlife.org/podcast/%d.mp3' % epno resp = requests.get(urlopn, stream=True, verify=verify) if not resp.ok: urlopn = 'http://audio.thisamericanlife.org/jomamashouse/ismymamashouse/%d.mp3' % epno resp = requests.get(urlopn, stream=True, verify=verify) if not resp.ok: print( "Error, could not download This American Life episode #%d. Exiting..." % epno) return with open(outfile, 'wb') as openfile: for chunk in resp.iter_content(65536): openfile.write(chunk) mp3tags = ID3() mp3tags['TDRC'] = TDRC(encoding=0, text=[u'%d' % year]) mp3tags['TALB'] = TALB(encoding=0, text=[u'This American Life']) mp3tags['TRCK'] = TRCK(encoding=0, text=[u'%d' % epno]) mp3tags['TPE2'] = TPE2(encoding=0, text=[u'Chicago Public Media']) mp3tags['TPE1'] = TPE1(encoding=0, text=[u'Ira Glass']) try: mp3tags['TIT2'] = TIT2(encoding=0, text=['#%03d: %s' % (epno, title)]) except: mp3tags['TIT2'] = TIT2( encoding=0, text=[codecs.encode('#%03d: %s' % (epno, title), 'utf8')]) mp3tags['TCON'] = TCON(encoding=0, text=[u'Podcast']) mp3tags.save(outfile)
def write_metadata(song_f: pathlib.Path): metadata_f = song_f.with_suffix('.json') if not metadata_f.exists(): print(f"No metadata for file '{song_f}'. Skipping.") return with open(metadata_f, 'r') as f: metadata = json.load(f) mp3 = MP3(str(song_f)) if mp3.tags is None: mp3.add_tags() tags = mp3.tags title = metadata.get('title') if title: tags.add(TIT2(encoding=3, text=title)) artist = metadata.get('artist') if artist: tags.add(TPE1(encoding=3, text=artist)) composer = metadata.get('composer') if composer: tags.add(TCOM(encoding=3, text=composer)) album = metadata.get('album') if artist: tags.add(TALB(encoding=3, text=album)) albumArtist = metadata.get('albumArtist') if albumArtist: tags.add(TPE2(encoding=3, text=albumArtist)) genre = metadata.get('genre') if genre: tags.add(TCON(encoding=3, text=genre)) tracknum = metadata.get('trackNumber') if tracknum: tags.add(TRCK(encoding=3, text=str(tracknum))) year = metadata.get('year') if year: tags.add(TDRC(encoding=3, text=str(year))) duration = metadata.get('durationMillis') if duration: tags.add(TLEN(encoding=3, text=str(duration))) albumart_f = song_f.with_name('folder.jpg') if albumart_f.is_file(): with open(albumart_f, 'rb') as f: tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc='Front Cover', data=f.read())) mp3.save()
def set_tags(filepath, trackinfo, albuminfo): try: audio = ID3(filepath) except ID3NoHeaderError: audio = ID3() if trackinfo['has_album'] is not False: audio.add(TALB(encoding=3, text=albuminfo['album_title'])) audio.add(TRCK(encoding=3, text=trackinfo['track_num'])) audio.add(TIT2(encoding=3, text=trackinfo['track_title'])) audio.add(TPE2(encoding=3, text=albuminfo['album_artist'])) audio.save(filepath)
def getMp3(self): audio = ID3(self.path) a = aa = '' if 'TPE1' in audio: a = audio['TPE1'].text[0] if 'TPE2' in audio: aa = audio['TPE2'].text[0] else: audio.add(TPE2(encoding=3, text=u"aa")) self.a = a self.aa = aa self.mp3 = audio
def dumpIt(entry): try: r = requests.get(entry['source'], stream=True) except Exception: return #filename ='{}.mp3'.format(entry['slug'].encode('utf8')) if not 'Content-Length' in r.headers: return filename = '{}.mp3'.format(entry['slug']) localSize = os.path.getsize(filename) if os.path.isfile(filename) else 0 remoteSize = int(r.headers['Content-Length']) if remoteSize <= localSize: print("[skip] filename:{}, local size:{}, remote size:{}".format( filename, localSize, remoteSize)) return f = open(filename, 'wb') print("[downloading] filename:{}, local size:{}, remote size:{}".format( filename, localSize, remoteSize)) for chunk in r.iter_content(1024): f.write(chunk) f.truncate() f.close() #write id3 tags try: audio = ID3(filename) except ID3NoHeaderError: audio = ID3() audio.add(TIT2(encoding=3, text=entry['title'])) audio.add(TPE1(encoding=3, text=entry['artist'])) audio.add(TPE2(encoding=3, text="IndieShuffle")) # audio.add(TALB(encoding=3,text="IndieShuffle")) audio.add(TCMP(encoding=3, text="1")) try: r = requests.get(entry['artwork'], stream=True) r.raw.decode_content = True #################################################################################################### #inMemBuffer = BytesIO() #with Image.open(r.raw) as img: #img.save(inMemBuffer,'png') #inMemBuffer.seek(0) #encoding=3 is required to enable MacOs preview to show the coverart icon #audio.add(APIC(encoding=3,type=3,mime='image/png',data=inMemBuffer.read())) #################################################################################################### #encoding=3 is required to enable MacOs preview to show the coverart icon audio.add( APIC(encoding=3, type=3, mime='image/jpeg', data=r.raw.read())) except Exception: pass audio.save(filename)
def setMP3Metadata(self): self.startingProcessing.emit() mp3_file = ID3(f"{self.parent.album()}/{self.parent.title()}.mp3") mp3_file['TPE1'] = TPE1(encoding=3, text=self.parent.artist()) mp3_file['TPE2'] = TPE2(encoding=3, text=self.parent.artist()) mp3_file['TPE3'] = TPE2(encoding=3, text=self.parent.artist()) mp3_file['TALB'] = TALB(encoding=3, text=self.parent.album()) mp3_file['TYER'] = TYER(encoding=3, text=self.parent.year()) mp3_file['TCON'] = TCON(encoding=3, text=self.parent.genre()) if self.parent.trackIndex() != (0,0): mp3_file["TRCK"] = TRCK(encoding=3, text=f"{self.parent.trackIndex()[0]}/{self.parent.trackIndex()[1]}") if self.parent.albumArtPath() != "": with open(self.parent.albumArtPath(), 'rb') as albumart: mp3_file['APIC'] = APIC( encoding=3, mime='image/png', type=3, desc=u'Cover', data=albumart.read() ) mp3_file.save() self.allDone.emit()
def add_mp3_metadata(file_path, title='Unknown', artist='Unknown', album='Unknown', index=0, year=""): """ adds tags for the mp3 file (artist, album etc.) :param file_path: the path of the mp3 file that was downloaded :type file_path: str :param title: the title of the song :type title: str :param artist: the artist of the song :type artist: str :param album: the album that the song is part of :type album: str :param index: the index of the song in the album :type index: str :param year: the year of release of the song/ album :type year: str :return: None """ try: print("replacing the file...") AudioSegment.from_file(file_path).export(file_path, format='mp3') print("writing tags on file...") print("{} {} {} {}".format(title, album, artist, index)) except FileNotFoundError as e: print("failed to convert {} to mp3 because file not found: {}".format(title, e)) return except Exception as e: print("unhandled exception in converting {} to mp3: {}".format(title, e)) return if title is 'Unknown': title = file_path.split('\\')[-1].split('.')[0] try: audio = ID3(file_path) except ID3NoHeaderError as e: audio = ID3() audio.add(TIT2(encoding=3, text=title)) audio['TIT2'] = TIT2(encoding=Encoding.UTF8, text=title) # title audio['TPE1'] = TPE1(encoding=Encoding.UTF8, text=artist) # contributing artist audio['TPE2'] = TPE2(encoding=Encoding.UTF8, text=artist) # album artist audio['TALB'] = TALB(encoding=Encoding.UTF8, text=album) # album audio['TRCK'] = TRCK(encoding=Encoding.UTF8, text=str(index)) # track number audio['TORY'] = TORY(encoding=Encoding.UTF8, text=str(year)) # Original Release Year audio['TYER'] = TYER(encoding=Encoding.UTF8, text=str(year)) # Year Of Recording audio.save(file_path)
def write_ID3v2(self): if MUTAGEN: if "MP3" in self.__audio_codec: try: tags = ID3(self.__filepath) except ID3NoHeaderError: tags = ID3() # Track number tags["TRCK"] = TRCK(encoding=3, text=unicode(self.get_tag("track_number"))) # Title tags["TIT2"] = TIT2(encoding=3, text=unicode(self.get_tag("title"))) # Artist tags["TPE1"] = TPE1(encoding=3, text=unicode(self.get_tag("artist"))) # Album tags["TALB"] = TALB(encoding=3, text=unicode(self.get_tag("album"))) # Year tags["TDRC"] = TDRC(encoding=3, text=unicode(self.get_tag("year"))) # Genre tags["TCON"] = TCON(encoding=3, text=unicode(self.get_tag("genre"))) # Comment tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=unicode(self.get_tag("comment"))) #tags["COMM"] = COMM(encoding=3, text=unicode(self.get_tag("comment"))) # Album artist tags["TPE2"] = TPE2(encoding=3, text=unicode(self.get_tag("album_artist"))) # Composer tags["TCOM"] = TCOM(encoding=3, text=unicode(self.get_tag("composer"))) # Disc number tags["TPOS"] = TPOS(encoding=3, text=unicode(self.get_tag("disc_number"))) # Cover tags["APIC"] = APIC(3, 'image/jpeg', 3, 'Front cover', self.get_tag("cover")) #tags.update_to_v24() tags.save(self.__filepath, v1=2)
def addID3(song_id, cover, lyrics, genre, artists, title, album_year, album_name, album_artist, album_track): audio = ID3(f'{song_id}.mp3') audio['APIC'] = APIC(encoding = 3, mime = 'image/jpeg', type = 3, data = cover) audio['USLT'] = USLT(encoding = 3, text = lyrics) audio['TIT2'] = TIT2(encoding = 3, text = title) audio['TPE1'] = TPE1(encoding = 3, text = artists) audio['TRCK'] = TRCK(encoding = 3, text = album_track) audio['TALB'] = TALB(encoding = 3, text = album_name) audio['TCON'] = TCON(encoding = 3, text = genre) audio['TPE2'] = TPE2(encoding = 3, text = album_artist) audio['TDRC'] = TDRC(encoding = 3, text = album_year) audio.save(v2_version=3, v23_sep='; ') logger.info(f'{title} tagged')