def add_albumart(albumart, song_title): """ Adds the album art to the song """ try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error('* Could not add album art', indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read() # Reads and adds album art ) ) audio.save() log.log('> Added album art')
def tag_mp3(file, path, d, album, type, *arg): audio = EasyMP3(file) audio['title'] = d['title'] audio['tracknumber'] = str(d['track_number']) try: audio['composer'] = d['composer']['name'] except KeyError: pass try: audio['artist'] = d['performer']['name'] # TRACK ARTIST except KeyError: if type == "track" or type == "playlist": audio['artist'] = d['album']['artist']['name'] # TRACK ARTIST else: audio['artist'] = album['artist']['name'] if type == "track" or type == "playlist": audio['genre'] = ', '.join(d['album']['genres_list']) # GENRE audio['albumartist'] = d['album']['artist']['name'] # ALBUM ARTIST audio['album'] = d['album']['title'] # ALBUM TITLE audio['date'] = d['album']['release_date_original'].split('-')[0] else: audio['GENRE'] = ', '.join(album['genres_list']) # GENRE audio['albumartist'] = album['artist']['name'] # ALBUM ARTIST audio['album'] = album['title'] # ALBUM TITLE audio['date'] = album['release_date_original'].split('-')[0] # YEAR audio.save() title = sanitize_filename(d['title']) os.rename(file, '{}/{:02}. {}.mp3'.format(path, d['track_number'], title)) os.remove('{}/cover.png'.format(path)) os.remove('{}/cover.jpg'.format(path))
def get_ext(link): if (link.endswith('.mp3')): return EasyMP3(link) elif (link.endswith('.m4a')): return EasyMP4(link) else: raise ValueError('Unable to read file extension.')
def _update_metadata_mp3(self,file_path,metadata): # print 'Updating metadata of ' + file_path audio = MP3(file_path) try: audio.add_tags() except error : pass cover = metadata[5].decode('utf8') fd = urllib.urlopen(cover) audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime='image/png' if cover.endswith('png') else 'image/jpeg', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=fd.read() ) ) fd.close() # always a good thing to do audio.save() audio = EasyMP3(file_path) audio["title" ] = metadata[0]# name audio["artist" ] = metadata[4]# artist audio["album" ] = metadata[3]# album audio.save()
def write_id3_tags(self, filepath: str, meta: dict): """Write metadata to the MP3 file :param filepath: name of mp3 file :param meta: dict of track metadata """ logging.debug(" Encoding process starting..") filename = filepath.rsplit('/', 1)[1][:-8] if not self.debugging: print_clean("\r({}/{}) [{}] :: Encoding: {}".format( self.track_num, self.num_tracks, "=" * 50, filename)) audio = MP3(filepath) audio.delete() audio["TIT2"] = TIT2(encoding=3, text=["title"]) audio.save(filename=None, v1=2) audio = MP3(filepath) if self.grouping and 'label' in meta: audio["TIT1"] = TIT1(encoding=3, text=meta["label"]) if self.embed_lyrics: audio["USLT"] = USLT(encoding=3, lang='eng', desc='', text=meta['lyrics']) if self.embed_art and self.album_art != None: with open(self.album_art, 'rb') as cover_img: cover_bytes = cover_img.read() audio["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=cover_bytes) audio.save() audio = EasyMP3(filepath) audio["tracknumber"] = meta['track'] audio["title"] = meta["title"] audio["artist"] = meta['artist'] audio["album"] = meta['album'] audio["date"] = meta["date"] audio.save() logging.debug(" Encoding process finished..") logging.debug(" Renaming:\n\t{} -to-> {}".format( filepath, filepath[:-4])) try: os.rename(filepath, filepath[:-4]) except WindowsError: os.remove(filepath[:-4]) os.rename(filepath, filepath[:-4]) if not self.debugging: print_clean("\r({}/{}) [{}] :: Finished: {}".format( self.track_num, self.num_tracks, "=" * 50, filename))
def create_song(fpath): """ parse music file metadata with Easymp3 and return a song model. """ try: metadata = EasyMP3(fpath) except MutagenError as e: logger.error('Mutagen parse metadata failed, ignore.') logger.debug(str(e)) return schema = EasyMP3MetadataSongSchema(strict=True) metadata_dict = dict(metadata) if 'title' not in metadata_dict: title = [fpath.rsplit('/')[-1].split('.')[0], ] metadata_dict['title'] = title metadata_dict.update(dict( url=fpath, duration=metadata.info.length * 1000 # milesecond )) try: song, _ = schema.load(metadata_dict) except ValidationError: logger.exeception('解析音乐文件({}) 元数据失败'.format(fpath)) return song
def checkfile(request): print "called checkfile" requestcopy = request.POST.copy() form = UploadForm(requestcopy) file = request.FILES['trackfile'] easy = EasyMP3(file) form.data['artistname'] = easy['artist'][0] form.data['artistdesc'] = 'description' form.data['albumname'] = easy['album'][0] if 'date' in easy: form.data['albumyear'] = easy['date'][0] form.data['trackname'] = easy['title'][0] form.data['tracknumber'] = easy['tracknumber'][0][0] form.data['tracklength'] = int(math.ceil(easy.info.length)) if 'confirmationbox' in form.data: print 'boxfull' createdatabaseentries(file, form) context = {'uploadform': form} return render(request, 'music_streaming/upload.html', context) else: context = {'uploadform': form} return render(request, 'music_streaming/upload.html', context)
def addTags(file): try: audio = EasyMP3(file) audio.tags = None audio["artist"] = getTrack().user[ "username"] # depending on who uploaded the song, this may not always be the actual artist of the song audio["title"] = getTrack().title audio["genre"] = getTrack().genre audio.save() artworkURL = getTrack( ).artwork_url # gets url of artwork for song provided... if "large" in artworkURL: # ...but we need to replace "large" with "t500x500"... artworkURL = artworkURL.replace( "large", "t500x500" ) # ...to get a decent sized photo that isn't pixelated for the cover art of the mp3 image_data = requests.get(artworkURL).content mime = 'image/jpeg' if '.jpg' in artworkURL: mime = 'image/jpeg' if '.png' in artworkURL: mime = 'image/png' audio = MP3(file, ID3=OldID3) audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime=mime, type=3, # 3 is for the cover image desc='Cover', data=image_data)) audio.save() except Exception as e: print(e)
def sort_button_click(self): """Event handler for sort_button presses""" folder_names = [] file_names = {} #Get the index of the combo box selection type_of_sort = self._sort_bybox.currentIndex() for path in self._paths: track = EasyMP3(path) #Extract the appropriate type of ID3 data based on type_of_sort if type_of_sort == 0: artist = track["artist"][0] folder_names.append(artist) file_names[path.rsplit('/', 1)[1]] = artist elif type_of_sort == 1: album = track["album"][0] folder_names.append(album) file_names[path.rsplit('/', 1)[1]] = album #Remove duplicates from list folder_names = list(dict.fromkeys(folder_names)) self.sort_files(folder_names, file_names) #Display a dialog showing success success = QMessageBox() success.setWindowTitle("Music Organizer - Success") success.setText("Success!") success.setStandardButtons(QMessageBox.Ok) success.exec()
def Rearrange(dir): files = os.listdir(dir) files = [ _ for _ in files if _.endswith('.mp3') or _.endswith('.m4a') or _.endswith('mp4') or _.endswith('.wav') or _.endswith('.webm') ] print("Found " + str(len(files)) + " files in " + dir + ".") for audio in files: try: f = EasyMP3(dir + "/" + audio) artist = f["artist"][0] if artist == "" or artist == "Unknown": artist = "unknown" album = f["album"][0] if album == "" or album == "Unknown": album = "unknown" if not os.path.exists(dir + "/" + artist): os.makedirs(dir + "/" + artist) if not os.path.exists(dir + "/" + artist + "/" + album): os.makedirs(dir + "/" + artist + "/" + album) os.rename(dir + "/" + audio, dir + "/" + artist + "/" + album + "/" + audio) except: print("Skipping file " + dir + "/" + audio)
def add_album_art(self, image_url): mp3 = EasyMP3(self.location, ID3=ID3) try: mp3.add_tags() except Exception as e: pass if not image_url: image_url = self.get_album_art(self.artist, self.mp3["album"][0]) try: mp3.tags.add( APIC( encoding = 3, mime = 'image/png', type = 3, desc = 'cover', data = urlopen(image_url).read() ) ) mp3.save() return image_url except Exception: return False
def make_m3u(pl_directory): track_list = ["#EXTM3U"] rel_folder = os.path.basename(os.path.normpath(pl_directory)) pl_name = rel_folder + ".m3u" for local, dirs, files in os.walk(pl_directory): dirs.sort() audio_rel_files = [ os.path.join(os.path.basename(os.path.normpath(local)), file_) for file_ in files if os.path.splitext(file_)[-1] in EXTENSIONS ] audio_files = [ os.path.abspath(os.path.join(local, file_)) for file_ in files if os.path.splitext(file_)[-1] in EXTENSIONS ] if not audio_files or len(audio_files) != len(audio_rel_files): continue for audio_rel_file, audio_file in zip(audio_rel_files, audio_files): try: pl_item = (EasyMP3(audio_file) if ".mp3" in audio_file else FLAC(audio_file)) title = pl_item["TITLE"][0] artist = pl_item["ARTIST"][0] length = int(pl_item.info.length) index = "#EXTINF:{}, {} - {}\n{}".format( length, artist, title, audio_rel_file) except: # noqa continue track_list.append(index) if len(track_list) > 1: with open(os.path.join(pl_directory, pl_name), "w") as pl: pl.write("\n\n".join(track_list))
def GetMetadata(self, fpath): from mutagen import MutagenError from mutagen.mp3 import EasyMP3 from mutagen.easymp4 import EasyMP4 from mutagen.flac import FLAC from mutagen.apev2 import APEv2 try: if (fpath.endswith("mp3") or fpath.endswith("ogg") or fpath.endswith("wma")): audio = EasyMP3(fpath) elif (fpath.endswith("m4a") or fpath.endswith("m4v") or fpath.endswith("mp4")): audio = EasyMP4(fpath) elif fpath.endswith("flac"): audio = FLAC(fpath) elif fpath.endswith("ape"): audio = APEv2(fpath) elif fpath.endswith("wav"): audio = dict() except MutagenError as e: logger.warning("Mutagen parse metadata failed, ignore.\n" "file: {}, exception: {}".format(fpath, str(e))) return None metadata_dict = dict(audio) for key in metadata_dict.keys(): metadata_dict[key] = metadata_dict[key][0] if "title" not in metadata_dict: title = os.path.split(fpath)[-1].split(".")[0] metadata_dict["title"] = title return metadata_dict
def get_file_info(file_path: str) -> tuple: """ Get mp3/mp4/flac tags from a file. :param file_path: the file path. :return: a tuple of (title, genre, artist, album, length) """ empty = lambda: (Path(file_path).name, None, None, None, None) tag = None try: if file_path.endswith('.flac'): tag = FLAC(file_path) elif file_path.endswith('.mp3'): tag = EasyMP3(file_path) elif file_path.endswith('m4a'): tag = EasyMP4(file_path) else: return empty() get = lambda t, s: t.get(s, None) or t.get(s.upper(), None) title = get(tag, 'title') or Path(file_path).name genre = get(tag, 'genre') artist = get(tag, 'artist') album = get(tag, 'album') length = tag.info.length if isinstance(length, (int, float)): minutes, seconds = divmod(length, 60) length_str = f'{int(minutes)}:{round(seconds):02d}' else: length_str = None return (__to_string(title), __to_string(genre), __to_string(artist), __to_string(album), length_str) except MutagenError: return empty() finally: del tag
def tag_mp3(file, path, d, album, istrack=True): audio = EasyMP3(file) audio["title"] = d["title"] audio["tracknumber"] = str(d["track_number"]) try: audio["composer"] = d["composer"]["name"] except KeyError: pass try: audio["artist"] = d["performer"]["name"] # TRACK ARTIST except KeyError: if istrack: audio["artist"] = d["album"]["artist"]["name"] # TRACK ARTIST else: audio["artist"] = album["artist"]["name"] if istrack: audio["genre"] = ", ".join(d["album"]["genres_list"]) # GENRE audio["albumartist"] = d["album"]["artist"]["name"] # ALBUM ARTIST audio["album"] = d["album"]["title"] # ALBUM TITLE audio["date"] = d["album"]["release_date_original"].split("-")[0] else: audio["GENRE"] = ", ".join(album["genres_list"]) # GENRE audio["albumartist"] = album["artist"]["name"] # ALBUM ARTIST audio["album"] = album["title"] # ALBUM TITLE audio["date"] = album["release_date_original"].split("-")[0] # YEAR audio.save() title = sanitize_filename(d["title"]) try: os.rename(file, "{}/{:02}. {}.mp3".format(path, d["track_number"], title)) except FileExistsError: print("File already exists. Skipping...")
def описание(file_name, title, artist): try: tags = EasyMP3(file_name) tags["title"] = title tags["artist"] = artist tags.save() except: pass
def clear_albums(path): import os from mutagen.mp3 import EasyMP3 if path[-1] != '/': path += '/' if path[0] == "~": path = os.path.expanduser(path) else: path = os.path.abspath(path) if not os.path.exists(path): print("Path error\n") return files = list(filter(lambda x: x.endswith('.mp3'), os.listdir(path))) found = False for name in files: track = EasyMP3(path + name) if not ('album' in track.keys() and '.' in track['album'][0]): continue found = True print(track['album'][0] + ' | y/n') key = input() if key == 'y': track['album'] = "" track.save() if not found: print('Не найдены') print('Завершено')
def write_metadata(metadata, mp3_file, thumbnail): audiofile = EasyMP3(mp3_file) try: audiofile.add_tags() except error: pass audiofile['title'] = metadata.title if metadata.author: audiofile['artist'] = metadata.author if metadata.album: audiofile['album'] = metadata.album if metadata.track_number != 0: audiofile['tracknumber'] = str(metadata.track_number) if metadata.first_release_date: audiofile['date'] = str(metadata.first_release_date) audiofile.save() if thumbnail is not None: audiofile = MP3(mp3_file) audiofile.tags.add(APIC(encoding=3, mime=thumbnail.mimetype, type=PictureType.COVER_FRONT, desc=u'Cover Front', data=open(thumbnail.filename).read())) audiofile.save()
def add_details(file_name, song_title, artist, album, lyrics=""): ''' Adds the details to song ''' tags = EasyMP3(file_name) tags["album"] = album tags["title"] = song_title tags["artist"] = artist tags.save() tags = ID3(file_name) tags["USLT::'eng'"] = ( USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)) tags.save(file_name) try: rename(file_name, song_title + '.mp3') except FileNotFoundError: pass print("\n [*]Song name : %s \n [*]Artist : %s \n [*]Album : %s \n " % ( song_title, artist, album))
def filesearch(): if request.method == 'POST': path = request.form['filename'] # 拡張子判定 root, ext = os.path.splitext(path) print(ext) if ext == '.m4a': tags = MP4(path).tags title = tags["\xa9nam"][0] artist = tags["\xa9ART"][0] album = tags["\xa9alb"][0] elif ext == '.mp3': tags = EasyMP3(path) title = tags['title'][0] artist = tags['artist'][0] album = tags['album'][0] else: title = "" artist = "" json_dict = {} json_dict["title"] = title json_dict["artist"] = artist url = get_url(json_dict) #print(title) return render_template('view.html', title=title, artist=artist, album=album, url=url)
def add_albumart(albumart, song_title): ''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: print(" > Could not add album art") return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read() # Reads and adds album art ) ) audio.save() print(" >Added Album Art")
def add_albumart(query, song_title): """ Adds the album art to a song by editing ID3 tags using Mutagen """ try: log.log_indented('* Trying to extract album art from Google.com') albumart = albumsearch.img_search_google(query) except: log.log_error('* Could not extract from Google, trying Bing') albumart = albumsearch.img_search_bing(query) try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read())) audio.save() log.log("> Added album art")
def append_to_tree(): time = [] for a in a_list: ## try: ## audio = TinyTag.get(a) ## except TinyTagException: ## pass ## time_ = int(audio.duration) audio_1 = MP3(a) time_ = int(audio_1.info.length) time.append((str(time_)+"seconds")) song_name = [] for b in a_list: try: audio_2 = EasyMP3(b) title = audio_2["title"] if title == None: title = "No title" else: title = title[0] song_name.append(title) except KeyError: song_name_ = [] for i in range(-1, -(len(b)+1), -1): if b[i] == "\\": break else: song_name_.append(b[i]) song_name_ = song_name_[::-1] song_name.append("".join(song_name_)) tree_list = [] for i, j, k in zip(song_name, time, a_list): tree_list.append((i, j, k)) for items in tree_list: tree.insert("", tk.END, values=items)
def get_mp3_infos(file): # initiate EasyMP3 class mp3 = EasyMP3(io.BytesIO(file)) # initialize id3_tags = dict() result = dict() # get length length = mp3.info.length result.update({"length": length}) # get tags #this way isn't suitable. only the tags are iterated which the file has. """ for key in mp3.tags: # mp3.tags return key of dictionary. here ie.: title, artist, genre, date. # artist name is at 0. position in array in a dictionary(or tuple?). ie: {"artist":["artist name]}. # we have to get it by giving index 0. value = mp3.tags.get(key)[0] result.update({key: value}) """ # get tags. this one works. for key in mp3.ID3.valid_keys.keys( ): # iterate through mp3 keys which in ID3 designated value = mp3.tags.get(key)[0] if mp3.tags.get( key ) is not None else None # keys in 0. position in array. sometimes key doesn't has value so None have to be returned id3_tags.update({key: value}) return id3_tags
def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None): """ Attempt to put ID3 tags on a file. """ try: audio = EasyMP3(filename) audio.tags = None audio["artist"] = artist audio["title"] = title if year: audio["date"] = str(year.encode('ascii', 'ignore')) if album: audio["album"] = album if track_number: audio["tracknumber"] = track_number if genre: audio["genre"] = genre audio.save() if artwork_url: artwork_url = artwork_url.replace('https', 'http') mime = 'image/jpeg' if '.jpg' in artwork_url: mime = 'image/jpeg' if '.png' in artwork_url: mime = 'image/png' if '-large' in artwork_url: new_artwork_url = artwork_url.replace('-large', '-t500x500') try: image_data = requests.get(new_artwork_url).content except Exception as e: # No very large image available. image_data = requests.get(artwork_url).content else: image_data = requests.get(artwork_url).content audio = MP3(filename, ID3=OldID3) audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime=mime, type=3, # 3 is for the cover image desc='Cover', data=image_data)) audio.save() except Exception as e: print(e)
def load(path): """ Loads a Song object from the given path :param path: :type path: str :type path: Path :return the newly loaded Song or None if could not read the audio file :rtype Song object :rtype Bool :raise TypeError when 'path' is not a String or a Path :raise ValueError when 'path' is resolved to a Directory or a non-existent location """ if not isinstance(path, (str, Path)): raise TypeError( "Song.path must be a valid OS Path or a Path-convertible String!" ) else: path = Path(path).absolute().resolve() if not path.exists() or not path.is_file(): raise ValueError( "Song.path must be a valid OS File-Path or a Path-convertible String!" ) try: temp_song = Song() audio_file = EasyMP3(path) if audio_file is not None and audio_file.tags is not None: # NOTE: the '[0]' in 'song_file.tags[...][0]' # is because the default return value is a single-item LIST. # This way, we avoid the '[...]' brackets in the Song's attributes if "title" in audio_file.tags: temp_song.set_title(str(audio_file.tags["title"][0])) else: temp_song.set_title(path.stem) if "artist" in audio_file.tags: temp_song.set_artist(str(audio_file.tags["artist"][0])) if "album" in audio_file.tags: temp_song.set_album(str(audio_file.tags["album"][0])) if temp_song.length() == "0": temp_song.set_length(audio_file.info.length) temp_song.set_path(path) logging.info("Audio file loaded: {}".format(temp_song.path())) return temp_song except MutagenError as e: logging.error("Audio file could NOT be loaded: {}" "Error: {}".format(path, e)) return None
def calculateSongDuration(musicfile): audiofile = EasyMP3(musicfile) # okreslenie liczby minut minutes = int(audiofile.info.length // 60) # okreslenie liczby sekund oraz dodatnie do liczby minut seconds = round(minutes + audiofile.info.length % 60) duration = str(minutes) + ":" + str(seconds) return duration
def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None, url=None, comment=None): """ Attempt to put ID3 tags on a file. Args: artist (str): title (str): year (int): genre (str): artwork_url (str): album (str): track_number (str): filename (str): url (str): """ try: audio = EasyMP3(filename) audio.tags = None audio["artist"] = artist audio["title"] = title if year: audio["date"] = str(year) if album: audio["album"] = album if track_number: audio["tracknumber"] = track_number if genre: audio["genre"] = genre if url: audio["website"] = url if artwork_url: artwork_url = artwork_url.replace('https', 'http') audio["website"] = artwork_url audio.save() # because there is software that doesn't seem to use WOAR we save url tag again as WXXX if url: audio = MP3(filename, ID3=OldID3) audio.tags.add(WXXX(encoding=3, url=url)) audio.save() return True except Exception as e: puts( colored.red("Problem tagging file: ") + colored.white("Is this file a WAV?")) return False
def mp3(): song = EasyMP3(file) write_keys(song) if exists(cover_img): song = ID3(file) song.update_to_v23() # better compatibility over v2.4 song.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='', data=open(cover_img, 'rb').read())) song.save(v2_version=3)
def add_album_art(self, image_url): mp3 = EasyMP3(self.location, ID3=ID3) mp3.tags.add( APIC(encoding=3, mime='image/png', type=3, desc='cover', data=urlopen(image_url).read())) mp3.save()