def add_id3_tags(t, file, cover): audio = ID3(file) # album audio.add(TALB(encoding=3, text=u'' + dict_cue['album'])) # genre audio.add(TCON(encoding=3, text=u'' + dict_cue['genre'])) # year audio.add(TYER(encoding=3, text=u'' + dict_cue['year'])) # compilation audio.add(TCMP(encoding=3, text=u'' + str(dict_cue['compilation']))) # track number audio.add(TRCK(encoding=3, text=u'' + str(t+1) + '/' + str(len(dict_cue['songs'])))) # artist if len(dict_cue['songs'][t]) == 3: audio.add(TPE1(encoding=3, text=u'' + dict_cue['songs'][t][1])) else: audio.add(TPE1(encoding=3, text=u'' + dict_cue['artist'])) # song title if len(dict_cue['songs'][t]) == 3: audio.add(TIT2(encoding=3, text=u'' + dict_cue['songs'][t][2])) else: audio.add(TIT2(encoding=3, text=u'' + dict_cue['songs'][t][1])) # cover if cover: audio.add(APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=open(cover, 'rb').read())) audio.save()
def _audio_tit2(atuple): audio, atag, advanced, _, _ = atuple if advanced: param = ast.literal_eval(atag) audio.add(TIT2(3, param[1])) else: audio.add(TIT2(3, atag))
def get_file_details(urlObj): ''' Function fetches information about media files. The output may be used as init parameters for a Main.Song object. @param urlObj: A metaUrl Object. @return url, filesize, SupportsHTTPRange, bitrate, title, artist, source, quality, videoid ''' if urlObj.isVideo: SupportsHTTPRange = True title, artist = utils.parse_title_from_filename(urlObj.title) ID3TagsToEdit = {} ID3TagsToEdit['TIT2'] = TIT2(encoding=3, text=title) ID3TagsToEdit['TPE1'] = TPE1(encoding=3, text=artist) dummyMP3 = utils.makeDummyMP3(config.temp_dir) utils.setID3Tags(ID3TagsToEdit, dummyMP3) ID3Info = [ config.itag_audio_bitrates[urlObj.itag.quality], title, artist, dummyMP3 ] elif urlObj.source.lower() in ["soundcloud", 'bandcamp']: SupportsHTTPRange = True ID3Info = get_id3info(urlObj.url) if not ID3Info[1] and not ID3Info[ 2]: # if there is no title and artist data in ID3 title, artist = utils.parse_title_from_filename(urlObj.title) ID3TagsToEdit = {} ID3TagsToEdit['TIT2'] = TIT2(encoding=3, text=title) ID3TagsToEdit['TPE1'] = TPE1(encoding=3, text=artist) dummyMP3 = utils.makeDummyMP3(config.temp_dir) utils.setID3Tags(ID3TagsToEdit, dummyMP3) ID3Info = [ID3Info[0], title, artist, dummyMP3] else: SupportsHTTPRange = is_ServerSupportHTTPRange(urlObj.url) ID3Info = get_id3info(urlObj.url) filesize = get_filesize(urlObj.url) bitrate, title, artist, ID3File = ID3Info # if file didn't have id3 tags, or if the 'title' and 'artist' values were empty if not ID3File or (not title and not artist): fn = ".".join(urlObj.url.split('/')[-1].split('.')[:-1]) title, artist = utils.parse_title_from_filename(fn) ID3TagsToEdit = {} ID3TagsToEdit['TIT2'] = TIT2(encoding=3, text=title) ID3TagsToEdit['TPE1'] = TPE1(encoding=3, text=artist) ID3File = utils.makeDummyMP3(config.temp_dir) utils.setID3Tags(ID3TagsToEdit, ID3File) return urlObj.url, filesize, SupportsHTTPRange, bitrate, title, artist, ID3File, \ urlObj.source, urlObj.duration, urlObj.itag, urlObj.videoid, \ urlObj.webpage_url, urlObj.view_count, urlObj.description
def setUp(self): self.frames = [ TIT2(text=["1"]), TIT2(text=["2"]), TIT2(text=["3"]), TIT2(text=["4"])] self.i = ID3Tags() self.i["BLAH"] = self.frames[0] self.i["QUUX"] = self.frames[1] self.i["FOOB:ar"] = self.frames[2] self.i["FOOB:az"] = self.frames[3]
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 add_metadata(mp3_dir, mp3_file_name, video_id): """ Adds metadata to an mp3 file :param mp3_dir: Directory of the mp3 file (Including filename) :param mp3_file_name: Just the filename of the mp3 file :param video_id: Youtube video id mp3 was extracted from """ metadata = get_metadata_obj(mp3_file_name, video_id) audio = MP3(mp3_dir, ID3=ID3) try: audio.add_tags() except: # Presumably would happen if the mp3 # already had tags, but that shouldn't # be possible with our setup pass audio.tags.add( APIC(encoding=3, mime="image/jpeg", type=3, desc="Thumbnail", data=open(metadata["thumbnail"], "rb").read())) audio.tags.add(TIT2(encoding=3, text=metadata["title"])) audio.tags.add(TALB(encoding=3, text=metadata["album"])) audio.tags.add(TPE1(encoding=3, text=metadata["artist"])) audio.save()
def apply_id3(self, cleaned_data): try: audio = EasyID3(self.files['mp3'].temporary_file_path()) except ID3NoHeaderError: audio = MP3(self.files['mp3'].temporary_file_path()) audio["TIT2"] = TIT2(encoding=3, text=[cleaned_data['title']]) audio.save() audio = EasyID3(self.files['mp3'].temporary_file_path()) audio = EasyID3(self.files['mp3'].temporary_file_path()) audio['title'] = cleaned_data['title'] audio['artist'] = unicode(cleaned_data['speaker']) if not cleaned_data['series']: album_title = 'Sermons from %s' % conf.KANISA_CHURCH_NAME else: album_title = unicode(cleaned_data['series']) audio['album'] = album_title audio['albumartistsort'] = conf.KANISA_CHURCH_NAME audio['organization'] = conf.KANISA_CHURCH_NAME audio['genre'] = 'Speech' # Not sure if this date format is right - the MP3 players I've # got to test with don't show anything more than the year. if 'date' in cleaned_data: audio['date'] = cleaned_data['date'].strftime('%Y%m%d') audio.save()
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_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 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 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 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 parse_tit2(self, id3, recording): if 'TIT2' not in id3 or id3['TIT2'].text[0] != recording.get('title'): print('Override title? [Y/n]') i = raw_input().lower() or 'y' if i == 'y': self.pop(id3, 'TIT2') id3.add(TIT2(encoding=3, text=recording['title']))
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 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 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 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 to_id3_tags(self, audio_path): """Loads an MP3 file and adds ID3v2.4 tags based on the given discogs entry""" audio = ID3(audio_path, v2_version=4) # Set album art album_art_url = self.get_album_art_url() if album_art_url: r = requests.get(album_art_url) audio.add(APIC( encoding=3, mime='image/jpeg', type=3, desc='Cover', data=r.content )) del r # Set title audio.add(TIT2(encoding=3, text=[self.track.title])) # Set artists audio.add(TPE1(encoding=3, text=self.get_artists())) # Set album audio.add(TALB(encoding=3, text=[self.get_release_title()])) # Set track number audio.add(TRCK(encoding=3, text=[self.track.position])) # Set labels labels = list(self.get_labels()) if len(labels) > 0: audio.add(TPUB(encoding=3, text=labels[0:1])) # Set genres audio.add(TCON(encoding=3, text=self.get_genres())) # Set year audio.add(TYER(encoding=3, text=[self.get_year()])) # for backwards compatibility with v2.3 # The timestamp fields are based on a subset of ISO 8601. When being as # precise as possible the format of a time string is # yyyy-MM-ddTHH:mm:ss (year, "-", month, "-", day, "T", hour (out of # 24), ":", minutes, ":", seconds), but the precision may be reduced by # removing as many time indicators as wanted. Hence valid timestamps # are # yyyy, yyyy-MM, yyyy-MM-dd, yyyy-MM-ddTHH, yyyy-MM-ddTHH:mm and # yyyy-MM-ddTHH:mm:ss. All time stamps are UTC. For durations, use # the slash character as described in 8601, and for multiple non- # contiguous dates, use multiple strings, if allowed by the frame # definition. audio.add(TDRL(encoding=3, text=[self.get_year()])) audio.add(TDOR(encoding=3, text=[self.get_year()])) # Set tagging time # aka right now # for completeness sake audio.add(TDTG(encoding=3, text=[datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M')])) # Write to disk audio.save()
def __bind_tags(song_file, song_info): audio = MP3(song_file['filepath'], ID3=ID3) try: audio.add_tags() except error: pass # set title audio.tags.add(TIT2(encoding=3, text=song_info['title'])) # set artist audio.tags.add(TPE1(encoding=3, text=song_info['artist'])) # set album cover response = requests.get(song_info['albumArtRef'][0]['url']) filepath = '/tmp/song_{0}.jpg'.format(song_file['filename']) with open(filepath, 'wb') as out: out.write(response.content) audio.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc='Album cover', data=open(filepath, 'rb').read())) audio.save(v2_version=3)
def id3Tag(self, file, title, album, artist, url): def getImageData(url): response = requests.get(url) img = Image.open(BytesIO(response.content)) (x, y) = img.size fixed = 150 out = img.resize((fixed, int(y * fixed / x)), Image.ANTIALIAS) imgByteArr = BytesIO() out.save(imgByteArr, format='JPEG') return imgByteArr.getvalue() audio = ID3(file) # Title if title: audio.add(TIT2(encoding=3, text=title)) # Album if album: audio.add(TALB(encoding=3, text=album)) # Artist if artist: audio.add(TPE1(encoding=3, text=artist)) if url: audio.add( APIC( encoding=3, # 3 is for utf-8 mime='image/png', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=getImageData(url) # data=open('resize.jpg','rb').read() #data=requests.get("https://www.baidu.com/img/bd_logo1.png?where=super").content )) audio.save()
def 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_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 start(self): songinfo, session, headers = self.songinfo, self.session, self.headers filename = os.path.join(songinfo['savedir'], songinfo['savename']+'.'+songinfo['ext']) cover_file = None checkDir(songinfo['savedir']) if os.path.exists(filename): print('already downloaed, skip') return True try: if songinfo['cover_url']: cover_file = os.path.join(songinfo['savedir'], "%s - cover.jpg" % filterBadCharacter(songinfo['album'])) if not os.path.exists(cover_file): with open(cover_file, 'wb') as f: r = session.get(songinfo['cover_url'], headers=headers) f.write(r.content) f.close() is_success = False with closing(session.get(songinfo['download_url'], headers=headers, stream=True, verify=False)) as response: total_size = int(response.headers['content-length']) chunk_size = 1024 if response.status_code == 200: label = '[FileSize]: %0.2fMB' % (total_size/1024/1024) with click.progressbar(length=total_size, label=label) as progressbar: with open(filename, "wb") as fp: for chunk in response.iter_content(chunk_size=chunk_size): if chunk: fp.write(chunk) progressbar.update(chunk_size) is_success = True # ensure there's ID3 tag in mp3 file if filename.endswith('mp3'): from mutagen.mp3 import MP3 from mutagen.id3 import TPE1, TALB, TIT2, TRCK, APIC mp3 = MP3(filename, v2_version=3) try: mp3.add_tags() except: pass mp3.tags['TPE1'] = TPE1(encoding=3, text=songinfo['singers']) mp3.tags['TALB'] = TALB(encoding=3, text=songinfo['album']) mp3.tags['TIT2'] = TIT2(encoding=3, text=songinfo['songname']) mp3.tags['TRCK'] = TRCK(encoding=3, text=str(songinfo['track'])) mp3.tags.add(APIC( encoding=3, mime='image/jpeg', type=3, desc='Cover', data=open(cover_file, 'rb').read() )) mp3.save(v2_version=3) if filename.endswith('m4a'): checkDir(os.path.join(songinfo['savedir'], 'output')) os.system("ffmpeg -i \"%s\" -i \"%s\" -map 0:0 -map 1:0 -metadata album=\"%s\" -metadata artist=\"%s\" -metadata title=\"%s\" -metadata track=\"%d/%d\" \"%s\"" %\ (filename, cover_file, songinfo['album'], songinfo['singers'], songinfo['songname'], songinfo['track'], songinfo['total'], os.path.join(songinfo['savedir'], 'output', songinfo['savename']+'.mp3'))) except Exception as e: print(e) is_success = False return is_success
def embedded_metadata(self,): # TODO use default image from show if no ep_image # not all files have metadate -- create if needed try: audio_meta = ID3(self.play_file_path) audio_meta.delete(delete_v1=True, delete_v2=True) except ID3NoHeaderError: audio_meta = ID3() image_format = self.image_file_path.split(".")[-1] # TODO accept only png / jpg with open(self.image_file_path, "rb") as ima: audio_meta.add( # image APIC( encoding=3, data=ima.read(), mime="image/{}".format(image_format), description="{}".format(self.play_file_name), ) ) audio_meta.add( # episode host TPE1(encoding=3, text=self.show,) ) audio_meta.add( # episode title TIT2(encoding=3, text=self.name,) ) audio_meta.save(self.play_file_path, v2_version=3) # since we embed image to play_file we can only check the total play_file_size here self.play_file_size = os.path.getsize(self.play_file_path) return True
class ID3Tags: title = ID3TagItem('TIT2', lambda i: i.text[0], lambda i: TIT2(encoding=Encoding.UTF8, text=i)) album = ID3TagItem('TALB', lambda i: i.text[0], lambda i: TALB(encoding=Encoding.UTF8, text=i)) artist = ID3TagItem('TPE1', lambda i: i.text[0], lambda i: TPE1(encoding=Encoding.UTF8, text=i)) sync_lrc = ID3TagItem( 'SYLT', lambda i: i.text, lambda i: SYLT( encoding=Encoding.UTF8, lang='eng', format=2, type=1, text=i)) unsync_lrc = ID3TagItem( 'USLT', lambda i: i.text, lambda i: USLT(encoding=Encoding.UTF8, lang='eng', text=i)) url = ID3TagItem('WXXX', lambda i: i.url, lambda i: WXXX(encoding=Encoding.UTF8, url=i)) cover = ID3TagItem( 'APIC', lambda i: i.data, lambda i: APIC( encoding=Encoding. LATIN1, # if other apple music/itunes can't display img mime='image/jpeg', # image/jpeg or image/png type=PictureType.COVER_FRONT, data=i)) def __init__(self, mp3path): self.file_path = mp3path try: self.tag = ID3(mp3path) except ID3NoHeaderError: self.tag = ID3() def save(self, file_path=None): file_path = file_path or self.file_path self.tag.save(file_path or self.file_path, v2_version=3)
def apply_meta(self, filename: str, meta: dict): album_cover = self._album_cover_download( meta["album"]["images"][0]["url"] ) album_artists = ", ".join(meta["album"]["artists"]) artists = ", ".join(meta["artist"]) lyric = LyricsSearcher(meta["name"], artists).search() tag = ID3(filename) tag["TIT2"] = TIT2(3, meta["name"]) # Title tag["TPE1"] = TPE1(3, artists) # Artist tag["TPE2"] = TPE2(3, album_artists) # Album Artist tag["TALB"] = TALB(3, meta["album"]["name"]) # Album Title tag["TRCK"] = TRCK(3, str(meta["track_number"])) # Track Number tag["TYER"] = TYER( 3, meta["album"]["released_at"].split("-")[0] ) # Released Year tag["APIC"] = APIC( encoding=3, mime="image/jpeg", type=3, desc="Album Cover", data=album_cover, ) # Album Cover if lyric is not None: tag["USLT"] = USLT(3, desc="", text=lyric) tag.save(v2_version=3) # ID3 os.rename( filename, self._safe_name("{} - {}".format(artists, meta["name"])) + ".mp3", )
def run(self): audio = MP3(mp3Arquivo) capaMp3 = '' if not capaArquivo: try: capaMp3 = audio.tags['APIC:'].data except: pass audio.delete() audio["TIT2"] = TIT2(encoding=3, text=unicode(strTitulo)) audio["TALB"] = TALB(encoding=3, text=unicode(strAlbum)) audio["TPE1"] = TPE1(encoding=3, text=unicode(strBanda)) audio["TDRC"] = TDRC(encoding=3, text=unicode(strAno)) audio["TRCK"] = TRCK(encoding=3, text=unicode(strTrack + '/' + strTotal)) audio["TPOS"] = TPOS(encoding=3, text=unicode(strNumAlbum + '/' + strTotalAlbum)) if capaArquivo or capaMp3: imagedata = capaArquivo or capaMp3 audio["APIC"] = APIC(encoding=3, mime='image/jpg', type=3, desc='', data=imagedata) audio.save() print 'Arquivo finalizado: ', self.mp3Arquivo
def setID3(self, lrc, info, path): tags = ID3(path) # remove old unsychronized lyrics if len(tags.getall("USLT")) != 0: tags.delall("USLT") if ('album' in info): tags.add(TALB(encoding=3, lang='', desc='', text=info['album'][0])) if ('title' in info): tags.add(TIT2(encoding=3, lang='', desc='', text=info['title'][0])) if ('artist' in info): tags.add(TPE1(encoding=3, lang='', desc='', text=info['artist'][0])) if ('cover' in info): tags.add( APIC(encoding=3, mime='image/png', type=3, desc='cover', data=requests.get(info['cover'][0], stream=True).raw.read())) for key, values in tags.items(): if key != 'APIC:cover': print('\t', key, ': ', values, sep='') tags.add(USLT(encoding=3, lang='eng', desc='aaa', text=lrc)) tags.save()
def 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)