def tag(filename, data): audio = File(filename) audio.delete() if isinstance(audio, mp3.MP3): audio.tags = easyid3.EasyID3() audio.update(data) audio.save()
def tag(self): data = self.get_parent_instance().metadata() with tempfile.NamedTemporaryFile(suffix='-musicdb.mp3') as f: # Download with default_storage.open(self.file.location) as g: contents = g.read() f.write(contents) f.flush() f.seek(0) audio = MutagenFile(f.name) audio.delete() if isinstance(audio, mp3.MP3): audio.tags = easyid3.EasyID3() audio.update(data) audio.save() self.length = int(audio.info.length) # Copy it back default_storage.delete(self.file.location) dst = default_storage.save(self.file.location, DjangoFile(f)) assert dst == self.file.location
def tag_reader(file): """ Read tags in audio files """ file_path = os.path.join(file[0], file[1]) if file[2] == "mp3": try: tag = easyid3.EasyID3(file_path) return tag except: return "None" # print "tag reading error/ no tag/empty tag for file "+file_path elif file[2] == "flac": try: flac_file = FLAC.load(file_path) flac_file.tags # ?? # ????? return "None" except: return "None" else: print file[2] + " filetype has no tag format processed." return "None"
def tag_scanner(music_path): if music_path.suffix == ".aiff" or music_path.suffix == ".aif": return aiff.AIFF(music_path) elif music_path.suffix == ".flac": return flac.FLAC(music_path) elif music_path.suffix == ".mp3": return easyid3.EasyID3(music_path) else: print("Invalid FileType")
def get_tag(args): abs_path = os.path.abspath(args.path) try: id3_tag = easyid3.EasyID3(abs_path) except id3.ID3NoHeaderError: id3_tag = File(abs_path, easy=True) id3_tag.add_tags() id3_tag.save() return id3_tag
def edit_id3(self, filename, album, artist, title=None): try: audio = easyid3.EasyID3(filename) except mutagen.id3.ID3NoHeaderError: audio = mutagen.File(filename, easy=True) audio.add_tags() audio["album"] = album audio["artist"] = artist audio["genre"] = "Podcast" if title: audio["title"] = title audio.save()
def __init__(self, mp3file): self.path = mp3file self.tags = tags = easyid3.EasyID3(str(mp3file)) # mp3_file.tags self.title = tags['title'][0] if 'title' in tags else Path(mp3file).stem # TODO get title from filename only? self.album = tags['album'][0] if 'album' in tags else None self.artist = tags['artist'][0] if 'artist' in tags \ else tags['albumartist'][0] if 'albumartist' in tags \ else None self.year = tags['date'][0] if 'date' in tags else None if 'tracknumber' in tags: m = re.match("(\\d+)(/(\\d+))?", tags['tracknumber'][0]) if m: self.tracknumber = int(m.group(1)) else: self.tracknumber = None
def tag(self): try: data = self.get_parent_instance().metadata() filename = os.path.join(settings.MEDIA_LOCATION, self.file.location) audio = MutagenFile(filename) audio.delete() if isinstance(audio, mp3.MP3): audio.tags = easyid3.EasyID3() audio.update(data) audio.save() except: self.tags_dirty = None self.save() raise finally: self.tags_dirty = False self.save()
def main(): """ Main code block """ json_file = "tags.json" with open(json_file, 'r') as fd: data = fd.read() data = json.loads(data) for line in data: path = pathlib.Path("{filename}".format(**line)) title = line['title'] artist = line['artist'] print("{} - {}".format(title, artist)) album = 'YouTube' if path.exists: mp3 = easyid3.EasyID3(str(path)) mp3["album"] = album mp3["artist"] = artist mp3["title"] = title mp3.save()
def processid3(filename, audioengine=mp3.MP3): '''Reads metadata from tracks that use the ID3 format - MP3, AAC''' f = easyid3.EasyID3(filename) title, anime, role, rolequal = part(f.get('title', _blank)[0]) label = f.get('label', _blank)[0] if not label: f_complex = id3.ID3(filename) case_map = {name.lower(): name for name in f_complex} to_try = ['tit3', 'txxx:subtitle', 'txxx:label', 'txxx:description'] for field in to_try: if field in case_map: label = f_complex[case_map[field]].text[0] break artist = f.get('artist', _unknown)[0] af = audioengine(filename) id = random_id() return [ metadata( ID=id, OriginalFileName=filename, Filename=canonicalFileName(id, artist, title, filename[-3:]), Tracktitle=title, Album=f.get('album', _blank)[0], Length=int(af.info.length * 1000), Anime=anime, Role=role, Rolequalifier=rolequal, Artist=f.get('artist', _blank)[0], Composer=f.get('composer', _blank)[0], Label=label, InMyriad="NO", Dateadded=datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")) ]
def save_stream(self, track, destination): if self.is_authenticated(): with open(destination, 'w+b') as stream_file: urls = self.webclient.get_stream_urls(track.get('storeId')) if len(urls) == 1: stream_file.write( self.webclient.session._rsession.get(urls[0]).content) range_pairs = [[int(s) for s in val.split('-')] for url in urls for key, val in parse_qsl(urlparse(url)[4]) if key == 'range'] for url, (start, end) in zip(urls, range_pairs): stream_file.truncate(start) stream_file.seek(0, 2) audio = self.webclient.session._rsession.get(url).content stream_file.write(audio) tag = easyid3.EasyID3() tag['title'] = track.get('title').__str__() tag['artist'] = track.get('artist').__str__() tag['album'] = track.get('album').__str__() tag['date'] = track.get('year').__str__() tag['discnumber'] = track.get('discNumber').__str__() tag['tracknumber'] = track.get('trackNumber').__str__() tag['performer'] = track.get('albumArtist').__str__() tag.save(destination) tag = mp3.MP3(destination) tag.tags.add( id3.APIC( 3, 'image/jpeg', 3, 'Front cover', urllib.urlopen( track.get('albumArtRef')[0].get('url')).read())) tag.save()
def getTitle(filename, use_metadata=False): ''' Get item title from file. If use_metadata is True, try reading title from metadata otherwise return file name as the title (without extension). Parameters ---------- filename : string Path to a file. use_metadata : bool Whether to use metadata. Default: False. Returns ------- title : string Item title. Examples -------- >>> media_dir = os.path.join("test", "media") >>> flac_file = os.path.join(media_dir, 'flac_with_tags.flac') >>> mp3_file = os.path.join(media_dir, 'mp3_with_tags.mp3') >>> getTitle(flac_file) 'flac_with_tags' >>> getTitle(flac_file, True) 'Test FLAC file with tags' >>> getTitle(mp3_file, True) 'Test media file with ID3 tags' ''' if use_metadata: try: # file with ID3 tags import eyed3 meta = eyed3.load(filename) if meta and meta.tag is not None: title_tag = meta.tag.title if (len(meta.tag.comments) > 0): description_tag = meta.tag.comments[0].text else: description_tag = title_tag return title_tag, description_tag except ImportError: pass try: import mutagen from mutagen import id3, mp4, easyid3, easymp4 from mutagen.mp3 import HeaderNotFoundError try: # file with ID3 tags title = easyid3.EasyID3(filename)["title"] if title: return title[0], title[0] except (id3.ID3NoHeaderError, KeyError): try: # file with MP4 tags title = easymp4.EasyMP4(filename)["title"] if title: return title[0], title[0] except (mp4.MP4StreamInfoError, KeyError): try: # other media types meta = mutagen.File(filename) if meta is not None: title = meta["title"] if title: return title[0], title[0] except (KeyError, HeaderNotFoundError): pass except ImportError: pass # fallback to filename as a title, remove extension though filename = os.path.basename(filename) title, _ = os.path.splitext(filename) return title, title
def fetch_id3_meta(song_filename): try: id3 = easyid3.EasyID3(song_filename) return {"title": id3["title"][0], "artist": id3["artist"][0]} except Exception: return {"title": None, "artist": None}