def test_zlib_utf16(self): from mutagen.id3 import TPE1 data = (b'\x00\x00\x00\x1fx\x9cc\xfc\xff\xaf\x84!\x83!\x93\xa1\x98A' b'\x01J&2\xe83\x940\xa4\x02\xd9%\x0c\x00\x87\xc6\x07#') tag = TPE1._fromData(_23._header, 0x80, data) self.assertEquals(tag.encoding, 1) self.assertEquals(tag, ['this is a/test']) tag = TPE1._fromData(_24._header, 0x08, data) self.assertEquals(tag.encoding, 1) self.assertEquals(tag, ['this is a/test'])
def test_zlib_latin1_missing_datalen(self): tag = TPE1._fromData( _24, 0x8, b'\x00\x00\x00\x0f' b'x\x9cc(\xc9\xc8,V\x00\xa2D\xfd\x92\xd4\xe2\x12\x00&\x7f\x05%' ) self.assertEquals(tag.encoding, 0) self.assertEquals(tag, ['this is a/test'])
def test_ql_0_12_missing_uncompressed_size(self): tag = TPE1._fromData( _24, 0x08, b'x\x9cc\xfc\xff\xaf\x84!\x83!\x93' b'\xa1\x98A\x01J&2\xe83\x940\xa4\x02\xd9%\x0c\x00\x87\xc6\x07#' ) self.assertEquals(tag.encoding, 1) self.assertEquals(tag, ['this is a/test'])
def test_zlib_latin1(self): from mutagen.id3 import TPE1 tag = TPE1._fromData( _24._header, 0x9, b'\x00\x00\x00\x0f' b'x\x9cc(\xc9\xc8,V\x00\xa2D\xfd\x92\xd4\xe2\x12\x00&\x7f\x05%' ) self.assertEquals(tag.encoding, 0) self.assertEquals(tag, ['this is a/test'])
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'])) lyric_data = self.get_lyric(info) id3.add(USLT(encoding=3, text=lyric_data)) if lyric_data else None #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'genre')) #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=info['comment'])) 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 convertToMp3(f): #print "Converting %s to mp3" % (f) m4tags = mp4Tag(f) #print "Converting %s - %s (%s) to mp3" % (m4tags.title, m4tags.artist, m4tags.album) cmd1 = ['faad', '-o', '-', f] f2 = "%s.mp3" % (f.rsplit('.', 1)[0], ) cmd2 = ['lame', '-', f2] p1 = Popen(cmd1, stdout=PIPE) p2 = Popen(cmd2, stdin=p1.stdout) p2.wait() try: mp3File = MP3(f2) mp3File['TIT2'] = TIT2(encoding=3, text=[m4tags.title]) mp3File['TPE1'] = TPE1(encoding=3, text=[m4tags.artist]) mp3File['TALB'] = TALB(encoding=3, text=[m4tags.album]) mp3File.save() print "%s converted to %s" % (f, f2) except: print >> sys.stderr, "Convert of %s failed." % f2 os.unlink(f)
def embed_music_metadata(title, filename, genius_url=None): try: music_info = get_music_info(title, genius_url) mp3 = MP3(filename) title = get_title(music_info) artist = music_info['primary_artist']['name'] mp3['TIT2'] = TIT2(encoding=3, text=[title]) mp3['TPE1'] = TPE1(encoding=3, text=[artist]) album_name, album_artist = get_album_info(music_info) mp3['TALB'] = TALB(encoding=3, text=[album_name]) mp3['TPE2'] = TPE2(encoding=3, text=[album_artist]) mp3['TCON'] = TCON(encoding=3, text=[music_info['genre']]) mp3['USLT::XXX'] = USLT(encoding=1, lang='XXX', desc='', text=music_info['lyrics']) try: artwork = requests.get(get_cover_art_url(music_info), stream=True) mp3['APIC:'] = APIC(encoding=3, mime="image/jpeg", type=3, desc='', data=artwork.raw.read()) except Exception as e: print(f"Failed to embed artwork for title: {title}", e) mp3.save() return f'{artist} - {title}', rename_file(title, artist, filename) except Exception as e: print(f"Failed to encode music data for title: {title}", e) return title, filename
def add_tag(file_path, thumbnail_url, title, artist, album): try: tags = ID3(file_path) except ID3NoHeaderError: print("Adding ID3 header.") tags = ID3() retry = 3 while retry >= 0: try: thumbnail_url_large = thumbnail_url + ".L" coverart_page = requests.get(thumbnail_url_large) if coverart_page.status_code == 404: coverart_page = requests.get(thumbnail_url) if coverart_page.status_code != 404: jpeg_file = BytesIO(coverart_page.content) image_processor = Image.open(jpeg_file) size = image_processor.size smaller, larger = size if size[0] < size[1] else size[::-1] box = ((larger - smaller) / 2, 0, (larger - smaller) / 2 + smaller, smaller) cropped = image_processor.crop(box) temp = BytesIO() cropped.save(temp, format="JPEG") temp.seek(0) coverart = temp.read() tags["APIC:"] = APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=coverart) if title is not None: tags["TIT2"] = TIT2(encoding=3, text=title) if artist is not None: tags["TPE1"] = TPE1(encoding=3, text=artist) if album is not None: tags["TALB"] = TALB(encoding=3, text=album) break except requests.ConnectionError as e: print(e) retry -= 1 tags.save(file_path, v1=0, v2_version=3)
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 tagMP3(conf, mediafile): # http://id3.org/id3v2.3.0#Attached_picture # http://id3.org/id3v2.4.0-frames (section 4.14) # https://stackoverflow.com/questions/7275710/mutagen-how-to-detect-and-embed-album-art-in-mp3-flac-and-mp4 # https://stackoverflow.com/questions/409949/how-do-you-embed-album-art-into-an-mp3-using-python img_stream, img_meta = imgConv(conf['tags']['img']) print('{0}: Now adding tags to {1}...'.format(datetime.datetime.now(), mediafile)) tag = ID3(mediafile) tag.add(TALB(encoding = 3, text = [conf['tags']['album']])) tag.add(APIC(encoding = 3, mime = img_meta['mime'], type = 3, desc = '{0} ({1})'.format(conf['tags']['artist'], conf['tags']['comment']), data = img_stream)) tag.add(TDRC(encoding = 3, text = ['{0}.{1}.{2}'.format(conf['tags']['year'], conf['episode']['month'], conf['episode']['day'])])) tag.add(TENC(encoding = 3, text = [conf['tags']['encoded']])) tag.add(TRCK(encoding = 3, text = [conf['tags']['track']])) tag.add(COMM(encoding = 3, #lang = '\x00\x00\x00', # I'm not sure why we're sending three NULLs, but best to be explicit. lang = 'eng', desc = 'Description provided by Podloader. https://git.square-r00t.net/Podloader', text = [conf['tags']['comment']])) tag.add(WXXX(encoding = 3, desc = conf['tags']['artist'], url = conf['tags']['url'])) tag.add(TCON(encoding = 3, text = [conf['tags']['genre']])) tag.add(TIT2(encoding = 3, text = [conf['episode']['pretty_title']])) tag.add(TPE1(encoding = 3, text = [conf['tags']['artist']])) tag.add(TCOP(encoding = 3, text = [conf['tags']['copyright']])) tag.save()
def add_tags(self, title, artist, cover, fullfilename): file = MP3(fullfilename, ID3=ID3) try: file.add_tags() except error: pass #Cover file.tags.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=urllib.request.urlopen(cover).read())) #Title file.tags.add(TIT2(encoding=3, text=title)) #Artist file.tags.add(TPE1(encoding=3, text=artist)) file.save()
def forwards(self, orm): "change tags in minuses to match data on site" for minus in orm.MinusRecord.objects.filter(type__type_name='audio'): if minus.file.path[-3:] == 'mp3': print "%s - %s" % (minus.title, minus.author.name) try: mp3info = MP3(minus.file.path) mp3info.update({ 'TPE1':TPE1(encoding =3, text = [minus.author.name]), 'TIT2':TIT2(encoding =3, text = [minus.title]), "COMM::'eng'":COMM(encoding=3, lang="eng", desc="", text=[u"downloaded from minus.lviv.ua"]), "COMM":COMM(encoding=3, lang="ukr", desc="", text=[u"Звантажено з minus.lviv.ua"]), 'TALB':TALB(encoding =3, text = [u"Записи користувача %s %s" %\ (minus.user.first_name, minus.user.last_name)]) }) mp3info.save() except: pass
def set_mp3_metadata(directory, song_properties, mp3_filename): """Set song metadata to MP3 file.""" # get byte format for album artwork url response = requests.get(song_properties["artwork"]) artwork_img = response.content audio = MP3(os.path.join(directory, mp3_filename), ID3=ID3) 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="Cover", data=artwork_img, )) audio["TALB"] = TALB(encoding=3, text=song_properties["album"]) audio["TPE1"] = TPE1(encoding=3, text=song_properties["artist"]) audio["TIT2"] = TIT2(encoding=3, text=song_properties["song"]) audio["TCON"] = TCON(encoding=3, text=song_properties["genre"]) audio.save()
def setArtistName(artist, name): app.logger.info('New artist name: {}'.format(name)) # update song artist title for song in artist.songs: app.logger.info('Updating artist for song {}'.format(song)) if song.path_name.lower().endswith('mp3'): tags = ID3(song.abs_path) tags["TPE1"] = TPE1(encoding=3, text=u'{}'.format(name)) tags.save(song.abs_path) elif song.path_name.lower().endswith('m4a'): tags = MP4(song.abs_path) raise Exception('Do total tracks for mp4') # see if new name does not already exists artist_by_name = Artist.query.filter(Artist.name == name, Artist.id != artist.id).first() if artist_by_name: app.logger.info('Artist already exists with name {}'.format(name)) for song in artist.songs: song = Song.query.get(song.id) # update album if song.album.artist.id != artist_by_name.id: album = song.album album.artist = artist_by_name db.session.commit() # update song song.artist = artist_by_name db.session.commit() return artist_by_name else: # update artist artist.name = name app.logger.info('Artist name updated') db.session.commit() return artist
async def addTags(temp, i, filename): async with aiohttp.ClientSession() as session: artist, name = temp if ('(' in name): name = name[:name.rfind('(')] url = f"https://orion.apiseeds.com/api/music/lyric/{artist}/{name}?apikey=9qfmD9f5MagVEjzWJP7QFEbpS1PjUgYdwCxD91gr9tFHzl2X5kLxqb2IAnyb8imE" json_str = await fetch(session, url) try: dic = json.loads(json_str) except: dic = {} # url = f"https://orion.apiseeds.com/api/music/lyric/{artist}/{name}?apikey=9qfmD9f5MagVEjzWJP7QFEbpS1PjUgYdwCxD91gr9tFHzl2X5kLxqb2IAnyb8imE" # dic = json.loads(requests.get(url).text) # create ID3 tag if not present try: tags = ID3(filename) except ID3NoHeaderError: print("Adding ID3 header;") tags = ID3() print(i, '. ', artist, name, end="") i += 1 tags["TIT2"] = TIT2(encoding=3, text=name) tags["TPE2"] = TPE2(encoding=3, text=artist) tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=u'mutagen comment') tags["TPE1"] = TPE1(encoding=3, text=artist) if "result" in dic: print(" -- add text", end='') tags[u"USLT::'eng'"] = (USLT(encoding=3, lang=u'eng', desc=u'desc', text=dic["result"]["track"]["text"])) tags.save(filename) print()
def post_adjustments(self): from mutagen.mp3 import MP3 from mutagen.id3 import TIT2, TALB, TPE1, APIC, COMM # If the title option for filename in self.new_items: audio = MP3(self.opts.dir + filename) print('-----------------------------------------') if self.opts.title: audio['TIT2'] = TIT2(encoding=3, text=filename[:-4]) toast_message('ID3 SET: `Title` --> {}'.format(filename[:-4])) if self.opts.album is not None: audio['TALB'] = TALB(encoding=3, text=self.opts.album) toast_message('ID3 SET: `Album` --> {}'.format( self.opts.album)) if self.opts.artist is not None: audio['TPE1'] = TPE1(encoding=3, text=self.opts.artist) toast_message('ID3 SET: `Artist` --> {}'.format( self.opts.artist)) if self.opts.message is not None: audio['COMM'] = COMM(encoding=3, text=self.opts.message) toast_message('ID3 SET: `COMMENT` --> {}'.format( self.opts.message)) if self.opts.cover is not None: try: img = open(self.opts.cover, 'rb').read() audio['APIC'] = APIC(encoding=3, data=img) except Exception: toast_message( '[{}] is not a valid JPEG file / URL. Abort.'.format( self.opts.cover)) return False toast_message('ID3 SET: `Album Jacket` --> {}'.format( self.opts.cover)) audio.save(self.opts.dir + filename) toast_message('Operation complete.')
def writeID3tag(self, info, audioFile): """ Writes the ID3 on mp3 """ # writing id3 tag audioPath = self.DL_DIR + audioFile + '.mp3' audio = ID3(audioPath) audio.add(TIT2(encoding=3, text=info[3])) # title audio.add(TPE1(encoding=3, text=info[2])) #artist audio.add(TALB(encoding=3, text=info[4])) # album audio.add(TRCK(encoding=3, text=str(info[5]))) # track Number audio.add(COMM(encoding=3, text=u'by <aflavio at gmail.com>')) # comments # writing artwork on mp3 artworkFile = audioFile + '.jpg' urllib.request.urlretrieve(info[6], self.TMP_DIR + artworkFile) pic = APIC(3, u'image/jpg', 3, u'Front cover', open(self.TMP_DIR + artworkFile, 'rb').read()) audio.add(pic) audio.save()
def write(): # img = open("/home/yang/PycharmProjects/网易云音乐音乐/"+"img.webp","wb") # res = session.get(url=songDdetails['singer_pic'],headers=headers) # img.write(res.content) # img.close() audio = ID3("/home/yang/Music/"+songDdetails['songName'] + '.mp3') # audio['APIC'] = APIC( # 插入专辑图片 # encoding=3, # mime='webp', # type=3, # desc=u'Cover', # data=img.read() # ) audio['TIT2'] = TIT2( # 插入歌名 encoding=3, text=songDdetails['songName'] ) audio['TPE1'] = TPE1( # 插入第一演奏家、歌手、等 encoding=3, text=songDdetails['singer'] ) audio.save()
def save(self): audio_path = self.search_dir + "/" + self.listbox.currentItem().text() audio_save_path = self.dest_dir + "/" + self.file_name_edit.text() if not self.artwork_bytes == None: if not self.checkbox.isChecked(): found = 0 for tag in self.audio_id3: if tag.startswith("APIC") and (PictureType.COVER_FRONT == 3): self.audio_id3[tag].data = self.artwork_bytes break if not found: self.audio_id3.add( APIC(encoding=3, mime='image/jpeg', type=3, data=self.artwork_bytes)) self.audio_id3.add( TPE1(encoding=3, text=self.artist_itunes_edit.text())) self.audio_id3.add(TIT2(encoding=3, text=self.title_itunes_edit.text())) self.audio_id3.add(TCON(encoding=3, text=self.genre_itunes_edit.text())) self.audio_id3.add(TALB(encoding=3, text=self.album_itunes_edit.text())) self.audio_id3.add( TYER(encoding=3, text=self.release_year_itunes_edit.text())) self.audio_id3.add( TRCK(encoding=3, text=self.track_no_itunes_edit.text())) self.audio_id3.save(v2_version=3) shutil.move(audio_path, audio_save_path) self.refresh_listbox() self.listbox.setCurrentRow(0)
def foreach(song, fname): download(song['videoId'], fname) audio = ID3(fname + '.mp3') if os.path.exists(fname + '.jpg'): with open(fname + '.jpg', 'rb') as albumart: audio['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=song['title'], data=albumart.read()) os.remove(fname + '.jpg') if song['artists'] is not None: audio['TPE1'] = TPE1(encoding=3, text=song['artists'][0]['name']) if song['album'] is not None: audio['TALB'] = TALB(encoding=3, text=song['album']['name']) audio['TIT2'] = TIT2(encoding=3, text=song['title']) audio['COMM'] = COMM(encoding=3, lang='eng', desc='desc', text='https://music.youtube.com/watch?v=' + song['videoId']) audio.save()
def __music_fix(self, file): m = self.__getMusicObj(file) print m.artic, m.title, m.lyfullname if m.artic and m.title and m.lyname and os.path.exists(m.lyfullname): print "ok", m.fullname return str = m.filename[:-4] if m.artic != None: str = "%s/%s" % (str, m.artic) if m.title: str = "%s/%s" % (str, m.title) lines = self.__searchLyric(artic="", title=str, check=False) print "search [%s] get [%d] lines" % (str, len(lines)) art = tit = None for n in lines: n = unicode(n, "GB18030").encode("UTF8") if re.search("\[ti:.*\]", n): tit = n[n.find("[ti:"):] tit = tit[4:tit.find("]")] if re.search("\[ar:.*\]", n): art = n[n.find("[ar:"):] art = art[4:art.find("]")] if art != None and tit != None: break print "[%s/%s]" % (art, tit) self.__saveLyric(lines, art, tit, True) if m.artic is None and m.title is None: id3obj = ID3() else: id3obj = ID3(file) if m.artic == None and art != None: id3obj.add(TPE1(encoding=3, text=art.decode("UTF8"))) if m.title == None and tit != None: if m.filename.find(tit) < 0: tit = m.filename[:-4] id3obj.add(TIT2(encoding=3, text=tit.decode("UTF8"))) id3obj.save(file)
def add_metadata_to_song(file_path, cover_path, song): # If no ID3 tags in mp3 file try: audio = MP3(file_path, ID3=ID3) except HeaderNotFoundError: print('Can\'t sync to MPEG frame, not an validate MP3 file!') return if audio.tags is None: print('No ID3 tag, trying to add one!') try: audio.add_tags() audio.save() except error as e: print('Error occur when add tags:', str(e)) return # Modify ID3 tags id3 = ID3(file_path) # Remove old 'APIC' frame # Because two 'APIC' may exist together with the different description # For more information visit: http://mutagen.readthedocs.io/en/latest/user/id3.html if id3.getall('APIC'): id3.delall('APIC') # add album cover id3.add( APIC( encoding= 0, # 3 is for UTF8, but here we use 0 (LATIN1) for 163, orz~~~ mime='image/jpeg', # image/jpeg or image/png type=3, # 3 is for the cover(front) image data=open(cover_path, 'rb').read())) # add artist name id3.add(TPE1(encoding=3, text=song['singer'][0]['name'])) # add song name id3.add(TIT2(encoding=3, text=song['songname'])) # add album name id3.add(TALB(encoding=3, text=song['albumname'])) id3.save(v2_version=3)
def modifySongInfo(songInfo: dict) -> str: """ 从字典中读取信息并修改歌曲的标签卡信息 """ id_card = File(songInfo['songPath']) 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'] try: id_card.save() except MutagenError: return 0 # 保存失败返回0 else: return 1 # 保存成功返回1
def setMetaTag(filename, title, artist, album, track, track_album, pic_data): audio = MP3(filename, ID3=ID3) try: audio.add_tags(ID3=ID3) except mutagen.id3.error: pass audio["TIT2"] = TIT2(encoding=3, text=title) audio["TPE1"] = TPE1(encoding=3, text=artist) audio["TALB"] = TALB(encoding=3, text=album) audio['TCON'] = TCON(encoding=3, text="Deemo") audio["TRCK"] = TRCK(encoding=3, text=str(track) + "/" + str(track_album)) audio["TCMP"] = TCMP(encoding=3, text="1") if pic_data is not None: audio.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=pic_data)) audio.save()
def updateMetadata(fileName: str, artist: str, title: str): # Create mutagen object meta = ID3(f'{fileName}.mp3') # Add known metadata meta.add(TPE1(encoding=3, text=artist)) # artist meta.add(TPE2(encoding=3, text=artist)) # album artist meta.add(TIT2(encoding=3, text=title)) # title # Add lyrics and album name from Genius genius_data = find_genius_data( removeTitleJunk(title, words_kept_in_parens1), artist) lyrics = bool(genius_data) and genius_data["lyrics"] default_album_name = f'{title} - Single' album_name = bool(genius_data) and genius_data["album_name"] album_art_downloaded = False if lyrics: meta.add(USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)) # lyrics if album_name: meta.add(TALB(encoding=3, text=album_name)) # album name album_art_path = f'{ALBUM_COVER_DIRECTORY}/{slugify(artist)} - {slugify(album_name)}.png' # If album art has already been downloaded if os.path.exists(album_art_path): album_art_downloaded = True else: album_art_downloaded = findAlbumArt.downloadAlbumArt( album_name, artist, album_name == default_album_name) if album_art_downloaded: with open(album_art_path, 'rb') as albumart: meta.add( APIC(encoding=3, mime='image/png', type=3, desc=u'Cover', data=albumart.read())) meta.save(v2_version=3)
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 on_gst_eos(self, bus, message): logging.info("EOS") # move the partial into completed if self.current_song.rating == RATE_LOVE: newlocation = "%s/%s - %s (loved).mp3" % (self.outfolder,clean_name(self.current_song.artist),clean_name(self.current_song.title)) else: newlocation = "%s/%s - %s.mp3" % (self.outfolder,clean_name(self.current_song.artist),clean_name(self.current_song.title)) os.rename(self.fs.get_property("location"),newlocation) # add mp3 tags f=ID3(newlocation) f.add(TIT2(encoding=3, text=self.current_song.title)) f.add(TALB(encoding=3, text=self.current_song.album)) f.add(TPE1(encoding=3, text=self.current_song.artist)) f.add(TCON(encoding=3, text=self.current_station.name)) if self.current_song.art_pixbuf is not None: # add the cover art # convert pure pixelmap to jpeg through file export because python Gtk is missing buffered function implementations self.current_song.art_pixbuf.savev(newlocation+".jpg", "jpeg", ["quality"], ["100"]) # get the file contents into the mp3 id2 tag v2.3/2.4 cover art f.add(APIC(3,u"image/jpg",3,u"Cover art",open(newlocation+".jpg", 'rb').read())) # first 3 = mutagen.id3.Encoding.UTF8, second 3 =mutagen.id3.PictureType.COVER_FRONT os.remove(newlocation+".jpg") f.save() self.next_song()
def modify(self): # ID3 info: # APIC: picture # TT2: title # TPE1: artist # TRCK: track number # TALB: album # USLT: lyric cover = open(f"covers/{self.album}jj.jpg", 'rb').read() id3 = ID3(f'test/{self.fname}') id3.add(APIC(3, 'image/jpeg', 3, 'Cover', cover)) id3.add(TT2(encoding=3, text=f"{self.title}")) id3.add(TPE1(encoding=3, text=f"{self.artist}")) id3.add(TALB(encoding=3, text=f"{self.album}")) # Lyrics try: # try to get XXX lyrics if id3["USLT::XXX"] and id3["USLT::XXX"] == "": # if exists but empty id3.add(USLT(encoding=3, text=f"{self.lyrics}")) # else, prob not empty, leave it except: # no X, try eng try: if id3["USLT::eng"] and id3["USLT::eng"] == "": # if exists but empty id3.add(USLT(encoding=3, text=f"{self.lyrics}")) # else, prob not empty, leave it except: # no lyrics, add id3.add(USLT(encoding=3, text=f"{self.lyrics}")) try: print(str(id3["USLT::eng"])[3], self.artist) except: print(str(id3["USLT::XXX"])[3], self.artist) id3.save(v2_version=3) # 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 id3_cook(directory, filename, item, track_num): pic_file = directory + '/cover.jpg' # pic file 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 Picture', data=open(pic_file).read())) audio.tags.add(TIT2(encoding=3, text=item['song'].decode('utf-8'))) audio.tags.add(TALB(encoding=3, text=item['album'].decode('utf-8'))) audio.tags.add(TPE1(encoding=3, text=item['artist'].decode('utf-8'))) audio.tags.add(TRCK(encoding=3, text=str(track_num).decode('utf-8'))) audio.tags.add( USLT(encoding=3, lang=u'eng', desc=u'desc', text=item['lyric'].decode('utf-8'))) audio.save()
def modify_id3_tags(track, mp3): debug_tags(mp3) try: tags = ID3(mp3) except ID3NoHeaderError: print("Adding ID3 header") tags = ID3() print("\nBEFORE MODIFICATION") print(tags.keys()) tags["TPE1"] = TPE1(encoding=3, text=track.artist) tags["TALB"] = TALB(encoding=3, text=track.album) tags["TIT2"] = TIT2(encoding=3, text=track.title) tags["TDRC"] = TDRC(encoding=3, text=track.year) tags["TRCK"] = TRCK(encoding=3, text=track.number) # tags["TPOS"] = TPOS(encoding=3, text=track.disc) tags["TCON"] = TCON(encoding=3, text=track.genres) tags.save(mp3) print("\nAFTER MODIFICATION") debug_tags(mp3)
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 set_mp3_headers(self, full_file_name, item): """给mp3文件加入一些标签信息""" mp3 = MP3(full_file_name) # 参与创作的艺术家 mp3["TPE1"] = TPE1(text=item["artist"]) mp3["TPE2"] = TPE2(text=item["artist"]) # 标题 mp3["TIT2"] = TIT2(text=item["name"]) # 发行日期 mp3["TDRC"] = TDRC(text=item["releaseDate"]) # 歌曲封面 atach picture mp3["APIC"] = APIC(mime='image/jpeg', type=3, data=self.my_get(item["albumpic"]).content) # 专辑 mp3["TALB"] = TALB(text=item["album"]) # 歌词 unsynchronised lyrics/text 因为不显示,所以就不设置了 # mp3["SYLT"] = SYLT(text=self.get_song_lyric(item["rid"]), type=1, format=2, encoding=3) # 流派 genre 一共有148 0: Blues mp3["TCON"] = TCON(text=item["content_type"]) # # 专辑中的排行 mp3["TRCK"] = TRCK(text="{}/".format(item["track"])) mp3.save()
def save(self, path): if self.song_type != "song": return False tmp_path = self.get_path() if tmp_path == False: return False try: audio = ID3(tmp_path) except ID3NoHeaderError: audio = ID3() audio['TIT2'] = TIT2(encoding=3, text=str(self.track).decode('utf-8')) audio['TPE1'] = TPE1(encoding=3, text=str(self.artist).decode('utf-8')) audio['TALB'] = TALB(encoding=3, text=str(self.album).decode('utf-8')) data = self.config.network.go_direct( self.cover_url.replace("%%", "400x400")) audio['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=data) audio.save(tmp_path) copyfile(tmp_path, path) return True
def test_lengthone_utf16(self): tpe1 = TPE1._fromData(_24, 0, b'\x01\x00') self.assertEquals(u'', tpe1) tpe1 = TPE1._fromData(_24, 0, b'\x01\x00\x00\x00\x00') self.assertEquals([u'', u''], tpe1)
def test_utf16_wrongnullterm(self): # issue 169 tpe1 = TPE1._fromData( _24, 0, b'\x01\xff\xfeH\x00e\x00l\x00l\x00o\x00\x00') self.assertEquals(tpe1, [u'Hello'])
def test_utf8(self): from mutagen.id3 import TPE1 tag = TPE1._fromData(_23._header, 0x00, b'\x03this is a test') self.assertEquals(tag.encoding, 3) self.assertEquals(tag, 'this is a test')
def test_badsync(self): frame = TPE1._fromData(_24, 0x02, b"\x00\xff\xfe") self.assertEqual(frame.text, [u'\xff\xfe'])
def test_datalen_but_not_compressed(self): from mutagen.id3 import TPE1 tag = TPE1._fromData(_24._header, 0x01, b'\x00\x00\x00\x06\x00A test') self.assertEquals(tag.encoding, 0) self.assertEquals(tag, ['A test'])