def searchMusicFile(songName, artistName): global numGenre global path_genre artistName = artistName.lower() songName = songName.lower() g = 0 while g < numGenre: mus_list = os.listdir(path_genre[g]) l = len(mus_list) i = 0 while i < l: mp3 = MP3File(path_genre[g]+mus_list[i]) mp3.set_version(VERSION_2) art = mp3.artist.lower() son = mp3.song.lower() if art == artistName and son == songName: return (path_genre[g] + mus_list[i]) i = i + 1 g = g + 1 return ""
def getMeta(fileName): audio = MP3(fileName) print(fileName) fileDets = {} if os.path.exists(fileName): mp3 = MP3File(fileName) try: tags = mp3.get_tags()["ID3TagV2"] for value in attrKeys.values(): fileDets[value] = tags[value.lower()] print(tags[value.lower()]) fileDets["Title"] = tags["song"] fileDets["Summary"] = tags["song"] fileDets["Summary"] = tags["song"] fileDets["Authors"] = tags["artist"] fileDets["Duration"] = audio.info.length fileDets["Size"] = audio.info.length fileDets["PubDate"] = None except: fileDets["Album"] = "The Dragon Reborn" fileDets["Title"] = "" fileDets["Summary"] = "" fileDets["Summary"] = "" fileDets["Authors"] = "Wheel of Time" fileDets["Duration"] = audio.info.length fileDets["Size"] = None fileDets["PubDate"] = None return fileDets
def dict_fill_from_bulk_mp3s(dict_input, mp3_location): for song in os.listdir(mp3_location): print('Currently processing dictionary fill for: ' + song) if song.endswith(".mp3"): # Defining starting file location of MP3 song_location = mp3_location + '\\' + song song_start = MP3File(song_location) song_start.set_version(VERSION_2) # Getting artist name and album name from MP3 tags artist_name = song_start.artist album_name = song_start.album else: print('This file is not an MP3! Moving on...') continue if artist_name == [] or album_name == []: print('This MP3 is missing necessary tags! Moving on...') continue # Otherwise goes on to add dictionary entries if artist or album is unique else: artist_check = False # Resets variable that keeps track of whether artist entry already exists # Checks to see if this artist already exists in the dictionary for entry in dict_input: if similar(entry, artist_name) > 0.85: print('There is already a dictionary entry for this artist.') artist_check = True # Variable is updated to represent artist being redundant for this song artist_name = entry break # If the artist entry already exists then... if artist_check: # Checks to see if the album for this artist already exists in the dictionary as well for entry in dict_input[artist_name]: if similar(entry, album_name) > 0.85: print("There is already a dictionary entry for this artist's album. Moving on...") break # If none of the album names are redundant, a new album name entry is created album_name = sanitize(album_name) dict_input[artist_name].append(album_name) print('A new album entry has been created for this artist in the dictionary. Moving on...') # If neither artist entry or album entry exists, this creates both of them else: artist_name = sanitize(artist_name) album_name = sanitize(album_name) dict_input[artist_name] = [album_name] print('A new artist entry with a corresponding album has been created in the dictionary. Moving on...') return dict_input
def getlist(self): self.musiclist = [] for file in os.listdir("music/"): if file.endswith(".mp3"): musicdata = {} filename = 'music/' + file if os.path.isfile(filename): # Get tags mp3 = MP3File(filename) musicdata['filename'] = filename musicdata['data'] = mp3.get_tags() # Get coverdata file = File(filename) if 'APIC:' in file.tags: coverdata = file.tags['APIC:'].data musicdata['cover'] = pil2cairo( Image.open(io.BytesIO(coverdata)), 128, 128) self.musiclist.append(musicdata) self.shufflelist() return self.musiclist
def import_song(self, path): ext = os.path.splitext(path)[-1].lower() if ext == ".mp3": try: mp3 = MP3File(path) try: tags = mp3.get_tags() except Exception: pass else: song_dict = dict(path=path) try: Song.objects.get(**song_dict) except Song.DoesNotExist: for tag_key, tag_dict in tags.items(): for song_key in ID3_FIELDS: if not song_dict.get(song_key): song_dict.update({song_key: tag_dict.get(song_key)}) try: Song.objects.create(**song_dict) except Exception: pass except Exception: pass
def write_mp3_tags(fout,targetdir): total_number_of_mp3 = do_initial_scan_for_mp3s(targetdir) current_time = time.time() count = 0 print("Writing out mp3 tags now") f = open(fout,"w+") f_errors = open(fout+".err","w+") f.write('|'.join(tags)+"\n") for root,dirs, files in os.walk(targetdir,topdown=False): for name in files: try: mp3 = MP3File(os.path.join(root,name)) except: continue data = [] for tag in tags: if tag != "filePath": try: data.append(str(mp3.get_tags()['ID3TagV1'][tag])) except: data.append('Not Assigned') data.append(os.path.join(root,name)) #try: f.write('|'.join(data)+"\n") except: f_errors.write(os.path.join(root,name) + "\n")
def myFun(fileName): audFetch = r"C:\Users\Dharmik\Desktop\New\songs\\" + fileName mp3 = MP3File(audFetch) mp3.set_version(VERSION_2) s = mp3.song y = mp3.year a = mp3.artist g = mp3.genre for i in s: if (i == "("): ind = s.index(i) s = s[0:ind] break elif (i == "["): ind = s.index(i) s = s[0:ind] re.sub('[^A-Za-z0-9]+', '', s) print("Song", s) os.rename(audFetch, r"C:\Users\Dharmik\Desktop\New\songs\\" + s + ".mp3") show_info(s, a, g, y)
def main(): args = def_params() bas_dir = os.path.dirname(os.path.realpath(__file__)) logging.debug("parametry:" + str(args)) mp3 = MP3File(args.file) mp3.set_version(VERSION_1) logging.debug("parametry:" + str(args)) if args.album is not None: mp3.album = args.album if args.artist is not None: mp3.artist = args.artist if args.song is not None: mp3.song = args.song if args.track is not None: # track powinno być number nie literal ! mp3.track = args.track if args.comment is not None: mp3.comment = args.comment else: mp3.comment = "" if args.genre is not None: mp3.genre = args.genre #to jest enum de facto - przyjmijmy że wpisujemy 0 if args.year is not None: mp3.year = args.year mp3.save() pprint(mp3.get_tags())
def get_track_features(token): ''' Function that retrieves track features for songs in database. :param token: Oath token of spotify :return: Dict of dicts that contains the features for all songs. ''' # Hardcoded names of directories that contain the songs. folders = ["classical", "rock", "pop", "electronic"] song_info = {folder: {} for folder in folders} # Retrieve song and artist from mp3 file. Loop over all 100 songs per dir. for folder in folders: for index in range(1, 101): mp3 = MP3File("./../../../songs/" + folder + "/" + str(index) + ".mp3") mp3.set_version(VERSION_2) # Retrieve song information from spotify id, song_name = get_track_id(mp3.song, mp3.artist, token) if (id != None): # put audio features in dict. audio_features = add_audio_features(id, token) audio_features["name"] = song_name song_info[folder][str(index)] = audio_features # this sleep prevents the api from being queried too often. sleep(0.10) return song_info
def setRjBuffer(filePath): rj = getRandomRj() if len(filePath) < 1: speech = 'You are listening to '+streamName + \ '. '+streamDescription + '. I am RJ '+rj[1]+'.' prepareRjBufferMp3(speech, rj) else: mp3 = MP3File(filePath) mp3.set_version(VERSION_2) if filePath.find('music/') > -1: speech = 'You are listening to '+streamName+'. I am RJ ' + \ rj[1]+'. Now, You will listen to ' + \ mp3.song+' by ' + mp3.artist+'.' #print(speech) prepareRjBufferMp3(speech, rj) elif filePath.find('news/news.mp3') > -1: speech = "Hello listeners, Its RJ "+rj[1]+". You are listening to "+streamName+". Now you will listen to the latest bulletin from BBC World Service." prepareRjBufferMp3(speech, rj) elif filePath.find('request/') > -1: speech = 'Hello listeners, Its RJ '+rj[1]+ \ '. You are listening to '+streamName+'. We just recieved a song request from ' + \ filePath.replace(requestPath,'').replace('.mp3','') + ' with love. Now you will listen to ' + \ mp3.song+' by ' + mp3.artist+'.' prepareRjBufferMp3(speech, rj)
def get_ID3v2_tags(mp3_file): """ Extract ID3v2 tags (artist, album, song) from *.mp3. If ID3v2 tags missing or not file permissions equate (artist=None, album=None, song=None). :param mp3_file: some *.mp3 :return: namedtuple(artist, album, song) """ try: audio = MP3File(mp3_file).get_tags().get('ID3TagV2') except AttributeError: audio = None except PermissionError: audio = None tags_mp3 = namedtuple('Tags', 'artist album song') tags = None if not audio: tags = tags_mp3(None, None, None) else: try: artist = del_system_char(audio.get('artist').strip()) except AttributeError: artist = None try: album = del_system_char(audio.get('album').strip()) except AttributeError: album = None try: song = del_system_char(audio.get('song').strip()) except AttributeError: song = None if artist and album and song: tags = tags_mp3(artist, album, song) return tags
async def download_track(session, track, progress_queue): output_file = os.path.join( output_directory, track['user']['username'], f"{track['title']}.mp3", ) chunk_size = 2**10 async with session.get(track['stream_url'], params={'client_id': client_id}) as response: target = f"{track['user']['username']} - {track['title']}" size = int(response.headers.get('content-length', 0)) or None position = await progress_queue.get() progress_bar = tqdm.tqdm( desc=target, total=size, position=position, leave=False, unit='iB', ascii=True, unit_scale=True, ) with open(output_file, 'wb+') as f: async for chunk in response.content.iter_chunked(chunk_size): f.write(chunk) progress_bar.update(len(chunk)) mp3 = MP3File(output_file) mp3.set_version(VERSION_BOTH) mp3.song = track['title'] mp3.artist = track['user']['username'] mp3.track = f"{track['track_num']}" mp3.album = 'Soundcloud' mp3.save() await progress_queue.put(position)
def download(mode, url, num): print(f"Downloading for {mode}") #Options ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'logger': MyLogger(), 'progress_hooks': [my_hook], 'outtmpl': folders[num][mode][0] + '/%(title)s.%(ext)s' } #Download the video and extract all the metadata with youtube_dl.YoutubeDL(ydl_opts) as ydl: info_dict = ydl.extract_info(url, download=True) video_title = info_dict.get('title', None) video_filename = '.'.join( ydl.prepare_filename(info_dict).split('.')[:-1]) + '.mp3' print(video_filename) #Edit mp3 tag. try: print(f"Editing artist tag to {mode.capitalize()}...") mp3 = MP3File(video_filename) mp3.artist = mode.title() mp3.save() insert_album_art(video_filename, info_dict['id']) print("Done!\n") except Exception as e: print("Error at editing mp3 tag.\n") print(e) #Backup if num != 3: try: print(f"Making a backup of {video_title}...") copy(video_filename, folders[num][mode][1]) print("Done!\n") except: print("Error at doing backup.\n") #Upload to google if num != 3: try: print(f"Uploading {video_title} to Google Music\n") print(f'With url {url}') mm = Musicmanager() mm.login(uploader_id='D0:50:99:83:B0:0C') mm.upload(video_filename) print("Done!\n") except Exception as e: print("Error at uploading the song to google:\n" + e)
def get_mp3_tags(file): from mp3_tagger import MP3File if util.get_file_extension(file).lower() != 'mp3': raise FileTypeError('File %s is not an mp3 file') # Create MP3File instance. mp3 = MP3File(file) return {'artist' : mp3.artist, 'author' : mp3.artist, 'song' : mp3.song, 'title' : mp3.song, \ 'album' : mp3.album, 'year' : mp3.year, 'track' : mp3.track, 'genre' : mp3.genre, 'comment' : mp3.comment}
def main(): print("Welcome to AutoTag") time.sleep(1) print("\nBefore using, please back up your music folder") time.sleep(4) print("PLEASE NOTE: ANY NON-AUDIO FILES WILL BE DELETED\n") time.sleep(2) print("MP3 files will be automatically tagged") print("Directories that cannot be tagged will be listed in 'Untagged.txt'") rootPath = os.path.dirname(os.path.realpath(__file__)) flacList = [] dirList = listDirectories() for folder in dirList: trackList, flacList = getFiles(folder, rootPath, flacList) if folder in flacList: continue trackList.sort() mp3 = MP3File(os.path.join(rootPath, folder, trackList[0])) mp3.set_version(VERSION_2) tags = mp3.get_tags() genre = getGenre(folder, tags) year = getYear(folder, tags) for track in trackList: mp3 = MP3File(os.path.join(rootPath, folder, track)) mp3.set_version(VERSION_2) tags = mp3.get_tags() skipFolder = trackTagger(tags, genre, year, folder, mp3, track) if skipFolder: successRate['Fail'] += 1 break trackList, flacList = getFiles(folder, rootPath, flacList) mp3 = MP3File(os.path.join(rootPath, folder, trackList[0])) mp3.set_version(VERSION_2) tags = mp3.get_tags() os.chdir("..") try: os.rename(folder, tags['artist'] + ' - ' + tags['album']) except ValueError as e: if folder not in untagged: untagged.append(" " + folder) successRate['Fail'] += 1 continue if folder not in untagged: successRate['Pass'] += 1 printUntagged()
def _fill_tags(self): mp3 = MP3File(os.path.join(self.download_path, f"{self}.mp3")) mp3.set_version(VERSION_BOTH) mp3.artist = self.author mp3.album = self.album mp3.song = self.name if self.track is not None: mp3.track = str(self.track) mp3.save()
def process(file): print(file) mp3 = MP3File(file) parts = file.split('/') mp3.set_version(VERSION_2) mp3.genre = parts[0] mp3.artist = parts[1] mp3.album = parts[2] mp3.song = parts[3]
def tag(file, artist="", track="", album=""): mp3 = MP3File(file) if artist: mp3.artist = artist if track: mp3.track = track if album: mp3.album = album mp3.save()
def main(): parser = argparse.ArgumentParser() parser.add_argument('path', help='System path to file.') args = parser.parse_args() path = args.path # Create MP3File instance. mp3 = MP3File(path) tags = mp3.get_tags() print(json.dumps(tags, indent=2, default=str)) exit()
def __init__(self, path): super(Mp3Info, self).__init__(path) mp3 = MP3File(self.path) tags = mp3.get_tags() for tag_version, tag_dict in tags.items(): for attr_name in self.attrib_list: if not getattr(self, attr_name): setattr(self, attr_name, tag_dict.get(attr_name, None))
def changeMetaTags(newPath, songPath, artist, album): try: mp3 = MP3File(newPath) mp3.artist = artist mp3.album = album mp3.save() os.remove(songPath) except Exception as e: print(e) pass
def fix_specific(filepath): print("Fixing genre for specific song...") mp3 = MP3File(filepath.replace("\\", "")) mp3.set_version(VERSION_2) old_genre = str(mp3.genre) print("Genre to fix: " + old_genre) new_genre = input("Enter new genre: ") mp3.genre = new_genre mp3.save() print("Fixed!")
def writeTags(self, path): mp3 = MP3File(path) mp3.song = self.data['title'] mp3.track = self.data['number'] if self.album: mp3.artist = self.album.data['artist'] mp3.album = self.album.data['title'] mp3.year = self.album.data['year'] mp3.save()
def on_done(filename): self.adapter.bot.sendChatAction(chat_id=chat_id, action=ChatAction.UPLOAD_AUDIO) mp3 = MP3File(filename) mp3.song = track_name mp3.artist = artists mp3.set_version(VERSION_BOTH) mp3.save() with open(filename, 'rb') as fp: self.adapter.bot.sendAudio(chat_id=chat_id, audio=fp, timeout=60)
def salvaID3(self, artista, album, titulo, musicaatual): try: mp3 = MP3File(musicaatual) mp3.artist = artista mp3.song = titulo mp3.album = album print(artista + ' - ' + album + ' ' + ' ' + titulo) mp3.save() except Exception as inst: print(type(inst)) print(artista + ' - ' + album + ' ' + ' ' + titulo)
def pegaTagsID3(self, musicaatual): try: print("entrando na pegatagsid3 " + musicaatual) mp3 = MP3File(musicaatual) tags = mp3.get_tags() return tags except: print("erro") # tag = mutagen.File(listofsongs[index], easy=True) # tag.add_tags()
def readNews(): global newsPath global basePath global bufferPath global currentGenre global currentArtist global currentSong global currentLyric newsList = os.listdir(newsPath) l = len(newsList) while l > 0: l = l - 1 if newsList[l] == "news.mp3": print("news preparing") setRjBuffer(newsPath+'news.mp3') os.system("sox "+newsPath +"news.mp3 -C 128 -r 44100 -c 2 "+newsPath+"newsOut.mp3") os.remove(newsPath+"news.mp3") print("news prepared") print('comming up next '+newsPath+'newsOut.mp3') mp3 = MP3File(newsPath+'newsOut.mp3') mp3.set_version(VERSION_2) mp3.song = "news" mp3.artist = "BBC World Service" mp3.save() tempFlag = 0 while int(currentPlayQueue) == 2 and initFlag == 1: if tempFlag == 0: print("waiting for previous stream...") tempFlag = 1 time.sleep(1) replace_line(playlistFile, 1, newsPath+"newsOut.mp3"+'\n') tempFlag = 0 while int(currentPlayQueue) == 1 and initFlag == 1: if tempFlag == 0: print("waiting for RJ...") tempFlag = 1 time.sleep(1) currentGenre = "news" currentLyric = "BBC World Service" return return
def update_song_data_from_file(self, song_path): """ Updates the abs path of a song from a given path and it reads the MP3 data. #TODO: support other types of audio """ updated = False if os.path.isfile(song_path): self._abs_path = song_path total_length = 0 # get attributes file_data = os.path.splitext(song_path) if file_data[1] == '.mp3': try: audio = MP3(song_path) total_length = audio.info.length except MutagenError as ex: config.logger.exception( f'Error when trying to get MP3 information for song in {song_path}' ) else: # div - total_length/60, mod - total_length % 60 mins, secs = divmod(total_length, 60) self._minutes = round(mins) self._seconds = round(secs) try: # get tags mp3_file = MP3File(song_path) tags = mp3_file.get_tags() tagsv2 = tags['ID3TagV2'] except Exception: config.logger.exception( f"Some exception occurred while reading MP3 tags for {song_path}." ) else: # TODO: do we really want to overwrite the band, album and title from the collection? if not self._band and 'artist' in tagsv2: self._band = tagsv2['artist'] if not self._album and 'album' in tagsv2: self._album = tagsv2['album'] if not self._title and 'song' in tagsv2: self._title = tagsv2['song'] updated = True else: config.logger.info(f"File {song_path} is not MP3.") else: raise Exception( f"File {song_path} does not exist. Could not set abs path for song." ) return updated
def atualizarArquivos(diretorio, nome_arquivo, artista, musica): barra = '\\' nome_completo_arquivo = diretorio + str(barra) + str(nome_arquivo) print(nome_completo_arquivo) mp3 = MP3File(nome_completo_arquivo) tags = mp3.get_tags() print(' Tags Antes:\n {}'.format(tags)) # Seta o novo artista mp3.artist = artista mp3.song = musica mp3.save() tags = mp3.get_tags() print(' Tags Depois:\n {}'.format(tags))
def test_main_generates_right_mp3_file(self): main = MainProgram() main.retag_files() self.assertTrue(os.path.exists(self.destination_folder)) complete_path = os.path.join(self.destination_folder, 'Play.mp3') self.assertTrue(os.path.exists(complete_path)) mp3_file = MP3File(complete_path) self.assertEqual('Jax-jones-years-years', mp3_file.artist) self.assertEqual('Play', mp3_file.song)