if not os.path.exists(path): path = '.'.join(path.split('.')[:-1]) + '.mp3' if not os.path.exists(path): path = '.'.join(path.split('.')[:-1]) + '.acc' if not os.path.exists(path): path = '.'.join(path.split('.')[:-1]) + '.wav' if not os.path.exists(path): print('Audio File was not found') print('{}, {}, {}, {}, {}, {}, {}, {}'.format( vid, track_name, artist_name, album_name, album_artist, image, album_artist, release_date)) continue dl_dir = "/tmp/{}-{}.jpg".format(safe_filename(track_name), safe_filename(artist_name)) download(image, dl_dir) audio_file = eyed3.load(path) audio_file.tag.artist = u"{}".format(artist_name) audio_file.tag.album = u"{}".format(album_name) audio_file.tag.album_artist = u"{}".format(album_artist) audio_file.tag.title = u"{}".format(track_name) audio_file.tag.release_date = u"{}".format(release_date) audio_file.tag.images.set(3, open(dl_dir, "rb").read(), "image/jpeg", u"") audio_file.tag.save() except Exception as e: print(e)
def test_XDOR_TDOR_Conversions(): test_file = "/tmp/xdortdrc.id3" tag = Tag() # 2.3 frames to 2.4 frame = frames.DateFrame(b"XDOR", "1990-06-24") tag.frame_set[b"XDOR"] = frame try: tag.save(test_file) # v2.4 is the default tag = eyed3.load(test_file).tag assert tag.version == ID3_V2_4 assert len(tag.frame_set) == 1 del tag.frame_set[b"TDOR"] assert len(tag.frame_set) == 0 finally: os.remove(test_file) tag = Tag() # 2.4 frames to 2.3 frame = frames.DateFrame(b"TDRC", "2012-10-21") tag.frame_set[frame.id] = frame try: tag.save(test_file, version=eyed3.id3.ID3_V2_3) tag = eyed3.load(test_file).tag assert tag.version == ID3_V2_3 assert len(tag.frame_set) == 2 del tag.frame_set[b"TYER"] del tag.frame_set[b"TDAT"] assert len(tag.frame_set) == 0 finally: os.remove(test_file)
def test_ObjectFrame_no_mimetype(audiofile, id3tag): # Setting no mime-type is invalid obj1 = ObjectFrame(object_data=b"Deep Purple") id3tag.frame_set[OBJECT_FID] = obj1 audiofile.tag = id3tag audiofile.tag.save() with patch("eyed3.core.parseError") as mock: file = eyed3.load(audiofile.path) assert mock.call_count == 2 obj1.mime_type = "Deep" audiofile.tag.save() with patch("eyed3.core.parseError") as mock: file = eyed3.load(audiofile.path) assert mock.call_count == 1 obj1.mime_type = "Deep/Purple" audiofile.tag.save() with patch("eyed3.core.parseError") as mock: file = eyed3.load(audiofile.path) mock.assert_not_called() obj1.object_data = b"" audiofile.tag.save() with patch("eyed3.core.parseError") as mock: file = eyed3.load(audiofile.path) assert mock.call_count == 1 assert file
def test_TermsOfUseFrame(audiofile, id3tag): terms = TermsOfUseFrame() assert terms.id == b"USER" assert terms.text == "" assert terms.lang == DEFAULT_LANG id3tag.terms_of_use = "F*****g MANDATORY!" audiofile.tag = id3tag audiofile.tag.save() file = eyed3.load(audiofile.path) assert file.tag.terms_of_use == "F*****g MANDATORY!" id3tag.terms_of_use = "F*****g MANDATORY!" audiofile.tag = id3tag audiofile.tag.save() file = eyed3.load(audiofile.path) assert file.tag.terms_of_use == "F*****g MANDATORY!" id3tag.terms_of_use = ("F*****g MANDATORY!", b"jib") audiofile.tag = id3tag audiofile.tag.save() file = eyed3.load(audiofile.path) assert file.tag.terms_of_use == "F*****g MANDATORY!" assert file.tag.frame_set[TOS_FID][0].lang == b"jib" id3tag.terms_of_use = ("F*****g MANDATORY!", b"en") audiofile.tag = id3tag audiofile.tag.save() file = eyed3.load(audiofile.path) assert file.tag.terms_of_use == "F*****g MANDATORY!" assert file.tag.frame_set[TOS_FID][0].lang == b"en"
def create_combined_audio(self, manifest): if manifest.get_issue_hash(self) == self.hash: print("%s: Combined audio already exists" % self) return if len(self.articles) < manifest.get_article_count(self): print("%s: Feed has fewer articles (%s) then preexisting combined audio (%s)." % (self, len(self.articles), manifest.get_article_count(self))) return # Download each article's MP3 file for article in self.articles: article.download() # Combine MP3 files into a single file combined = AudioSegment.empty() chapters = [] _chap_start = 0 _chap_end = 0 for article in self.articles: print("%s: Found %s with length of %s seconds" % (self, article, article.audio.duration_seconds)) _chap_end = _chap_start + (article.audio.duration_seconds * 1000) combined += article.audio chapters.append((article.title, int(_chap_start), int(_chap_end))) _chap_start = _chap_end # Export the new combined file combined.export(self.local, format=FORMAT, bitrate="128k") # Extract the cover image from the first article MP3 cover_id3 = eyed3.load(self.articles[0].local) cover_img_frame = cover_id3.tag.images.get('') # Set cover image on combined file id3 = eyed3.load(self.local) id3.tag.images._fs[b'APIC'] = cover_img_frame # Add chapter markers to the combined file index = 0 child_ids = [] for chapter in chapters: element_id = ("chp{}".format(index)).encode() title, start_time, end_time = chapter new_chap = id3.tag.chapters.set(element_id, (start_time, end_time)) new_chap.sub_frames.setTextFrame(b"TIT2", "{}".format(title)) child_ids.append(element_id) index += 1 id3.tag.table_of_contents.set(b"toc", toplevel=True, ordered=True, child_ids=child_ids) # Update the manifest with the new info manifest.save_issue(self, combined) print("%s: Created combined audio with length of %s seconds" % (self, combined.duration_seconds)) print("%s: Saved to %s" % (self, self.local)) print("%s: Chapters:" % self) for chap in id3.tag.chapters: print("%s: - %s" % (self, chap.sub_frames.get(b"TIT2")[0]._text)) # Save ID3 tags id3.tag.save()
def testAddRemoveLyrics(self, version=id3.ID3_DEFAULT_VERSION): if version[0] == 1: # No support for this in v1.x return comment = "Why can't I be you?" for i, (c, d, l) in enumerate([(comment, "c0", None), (comment, "c1", None), (comment, "c2", 'eng'), ("¿Por qué no puedo ser tú ?", "c2", 'esp'), ]): darg = ":{}".format(d) if d else "" larg = ":{}".format(l) if l else "" opts = ["--add-comment={c}{darg}{larg}".format(**locals()), self.test_file] self._addVersionOpt(version, opts) with RedirectStdStreams() as out: args, _, config = main.parseCommandLine(opts) retval = main.main(args, config) assert (retval == 0) af = eyed3.load(self.test_file) assert (af is not None) assert (af.tag is not None) tag_comment = af.tag.comments.get(d or "", lang=utils.b(l if l else "eng")) assert (tag_comment.text == c) assert (tag_comment.description == d or "") assert (tag_comment.lang == utils.b(l if l else "eng")) for d, l in [("c0", None), ("c1", None), ("c2", "eng"), ("c2", "esp"), ]: larg = ":{}".format(l) if l else "" opts = ["--remove-comment={d}{larg}".format(**locals()), self.test_file] self._addVersionOpt(version, opts) with RedirectStdStreams() as out: args, _, config = main.parseCommandLine(opts) retval = main.main(args, config) assert (retval == 0) af = eyed3.load(self.test_file) tag_comment = af.tag.comments.get(d, lang=utils.b(l if l else "eng")) assert tag_comment is None assert (len(af.tag.comments) == 0)
def update_library(): lib = [] print(os.listdir(app.config['MUSIC_DIR'])) for (path, dirs, files) in os.walk(app.config['MUSIC_DIR']): for f in files: if f.endswith(".mp3"): abs_path = os.path.join(path, f) print("Abs: " + abs_path) rel_path = abs_path[len(app.config['MUSIC_DIR'])+1:] db_song = g.db.execute(u"select id, last_update from song where path=?", [rel_path]).fetchone() if not db_song: print(abs_path) print("New song: " + rel_path) data = eyed3.load(abs_path) lib.append({'id':-1, 'artist':data.tag.artist, 'title':data.tag.title, 'album': data.tag.album, 'filename':rel_path}) else: if db_song[1] < os.path.getmtime(abs_path): print("Update song: " + rel_path) data = eyed3.load(abs_path) lib.append({'id': db_song[0], 'artist':data.tag.artist, 'title':data.tag.title, 'album': data.tag.album, 'filename':rel_path}) count_new = 0 count_update = 0 for song in lib: db_artist = g.db.execute(u"select id from artist where name=?", [song['artist']]).fetchone() artist_id = -1 if db_artist: artist_id = db_artist[0] else: cur = g.db.execute(u"insert into artist (name) values (?)", [song['artist']]) artist_id = cur.lastrowid db_album = g.db.execute(u"select id from album where name=?", [song['album']]).fetchone() album_id = -1 if db_album: album_id = db_album[0] else: cur = g.db.execute(u"insert into album (artist_id, name) values (?, ?)", [artist_id, song['album']]) album_id = cur.lastrowid if song['id'] == -1: g.db.execute(u"insert into song (name, artist_id, album_id, path, last_update) values (?, ?, ?, ?, ?)", [song['title'], artist_id, album_id, song['filename'], time.time()]) count_new += 1 else: g.db.execute(u"update song set name=?, artist_id=?, album_id=?, path=?, last_update=? where id=?", [song['title'], artist_id, album_id, song['filename'], time.time(), song['id']]) count_update += 1 g.db.commit() return (count_new, count_update)
def testIssue76(audiofile): """ https://github.com/nicfit/eyeD3/issues/76 """ tag = audiofile.initTag(ID3_V2_4) tag.setTextFrame("TPE1", "Confederacy of Ruined Lives") tag.setTextFrame("TPE2", "Take as needed for pain") tag.setTextFrame("TSOP", "In the name of suffering") tag.setTextFrame("TSO2", "Dope sick") tag.save() audiofile = eyed3.load(audiofile.path) tag = audiofile.tag assert (set(tag.frame_set.keys()) == set([b"TPE1", b"TPE2", b"TSOP", b"TSO2"])) assert tag.getTextFrame("TSO2") == "Dope sick" assert tag.getTextFrame("TSOP") == "In the name of suffering" assert tag.getTextFrame("TPE2") == "Take as needed for pain" assert tag.getTextFrame("TPE1") == "Confederacy of Ruined Lives" audiofile.tag.lyrics.set("some lyrics") audiofile = eyed3.load(audiofile.path) tag = audiofile.tag assert (set(tag.frame_set.keys()) == set([b"TPE1", b"TPE2", b"TSOP", b"TSO2"])) assert tag.getTextFrame("TSO2") == "Dope sick" assert tag.getTextFrame("TSOP") == "In the name of suffering" assert tag.getTextFrame("TPE2") == "Take as needed for pain" assert tag.getTextFrame("TPE1") == "Confederacy of Ruined Lives" # Convert to v2.3 and verify conversions tag.save(version=ID3_V2_3) audiofile = eyed3.load(audiofile.path) tag = audiofile.tag assert (set(tag.frame_set.keys()) == set([b"TPE1", b"TPE2", b"XSOP", b"TSO2"])) assert tag.getTextFrame("TSO2") == "Dope sick" assert tag.getTextFrame("TPE2") == "Take as needed for pain" assert tag.getTextFrame("TPE1") == "Confederacy of Ruined Lives" assert tag.frame_set[b"XSOP"][0].text == "In the name of suffering" # Convert to v2.4 and verify conversions tag.save(version=ID3_V2_4) audiofile = eyed3.load(audiofile.path) tag = audiofile.tag assert (set(tag.frame_set.keys()) == set([b"TPE1", b"TPE2", b"TSOP", b"TSO2"])) assert tag.getTextFrame("TSO2") == "Dope sick" assert tag.getTextFrame("TPE2") == "Take as needed for pain" assert tag.getTextFrame("TPE1") == "Confederacy of Ruined Lives" assert tag.getTextFrame("TSOP") == "In the name of suffering"
def test_write_full_eyed3(self): self.test_read_full_eyed3() audio = eyed3.load(fullMP3) audio.tag.title = unicode("new_title") # titre # sous-titre audio.tag.frame_set["POPM"][0].rating = 64 # notation # commentaire audio.tag.artist = unicode("new_artist") # artiste ayant participé # artiste de l'album audio.tag.album = unicode("new_album") # album # année audio.tag.track_num = 22 # n° audio.tag.genre = eyed3.id3.Genre(u"new_genre") # genre audio.tag.publisher = unicode("new_publisher") # éditeur # encodé par audio.tag.artist_url = unicode("new_urlAuteur") # URL de l'auteur # compositeur # chef d'orchestre # description du groupe # ambiance audio.tag.disc_num = 2 # partie du coffret # clé d'origine audio.tag.bpm = 222 # battements par minute # partie d'une compilation audio.tag.save() audio = eyed3.load(fullMP3) self.assertEqual(audio.tag.title, "new_title") # titre # sous-titre self.assertEqual(audio.tag.frame_set["POPM"][0].rating, 64) # notation # commentaire self.assertEqual(audio.tag.artist, "new_artist") # artiste ayant participé # artiste de l'album self.assertEqual(audio.tag.album, "new_album") # album # année self.assertEqual(audio.tag.track_num[0], 22) # n° self.assertEqual(audio.tag.genre.name, "new_genre") # genre self.assertEqual(audio.tag.publisher, "new_publisher") # éditeur # encodé par self.assertEqual(audio.tag.artist_url, "new_urlAuteur") # URL de l'auteur # compositeur # chef d'orchestre # description du groupe # ambiance self.assertEqual(audio.tag.disc_num[0], 2) # partie du coffret # clé d'origine self.assertEqual(audio.tag.bpm, 222) # battements par minute
def test_write_none_eyed3(self): self.test_read_none_eyed3() audio = eyed3.load(noneMP3) audio.tag.title = unicode("title") # titre # sous-titre audio.tag.frame_set["POPM"] = eyed3.id3.frames.PopularityFrame(id="POPM", rating=1) # notation # commentaire audio.tag.artist = unicode("artist") # artiste ayant participé # artiste de l'album audio.tag.album = unicode("album") # album # année audio.tag.track_num = 11 # n° audio.tag.genre = eyed3.id3.Genre(u"genre") # genre audio.tag.publisher = unicode("publisher") # éditeur # encodé par audio.tag.artist_url = unicode("urlAuteur") # URL de l'auteur # compositeur # chef d'orchestre # description du groupe # ambiance audio.tag.disc_num = 1 # partie du coffret # clé d'origine audio.tag.bpm = 111 # battements par minute # partie d'une compilation audio.tag.save() audio = eyed3.load(noneMP3) self.assertEqual(audio.tag.title, "title") # titre # sous-titre self.assertEqual(audio.tag.frame_set["POPM"][0].rating, 1) # notation # commentaire self.assertEqual(audio.tag.artist, "artist") # artiste ayant participé # artiste de l'album self.assertEqual(audio.tag.album, "album") # album # année self.assertEqual(audio.tag.track_num[0], 11) # n° self.assertEqual(audio.tag.genre.name, "genre") # genre self.assertEqual(audio.tag.publisher, "publisher") # éditeur # encodé par self.assertEqual(audio.tag.artist_url, "urlAuteur") # URL de l'auteur # compositeur # chef d'orchestre # description du groupe # ambiance self.assertEqual(audio.tag.disc_num[0], 1) # partie du coffret # clé d'origine self.assertEqual(audio.tag.bpm, 111) # battements par minute
def song_information(): song_info_list = [] print ( "********************************************************************************************************") duration = eyed3.load(sarki).info.time_secs print(duration) for song in songs: if song.endswith(".mp3"): path = songs_path + song audiofile = eyed3.load(path) song_info = {'artist': audiofile.tag.artist, 'album': audiofile.tag.artist, 'title': audiofile.tag.title, 'path': path, 'genre': audiofile.tag.genre} song_info_list.append(song_info) return render_template("index.html", song_info_list=song_info_list)
def process(self, md5id, filename): if not self.match(filename): return False, None # store by artists if not os.path.exists(filename): dst = os.path.join(self.store_path, os.path.basename(filename)) return True, dst tag = eyed3.load(filename) artist = None album = None try: artist = tag.tag.artist album = tag.tag.album artist = artist.encode('utf-8') album = album.encode('utf-8') except AttributeError as e: pass if artist and album: dst = os.path.join(self.store_path, str(artist), album, self.basename) elif artist and not album: dst = os.path.join(self.store_path, str(artist), self.basename) elif not artist and album: dst = os.path.join(self.store_path, str(artist), self.basename) else: dst = os.path.join(self.store_path, "unknown", self.basename) return True, dst
def modify(folderPath): """ Method to update metadata and rename all mp3 files in folderPath. """ filesList = os.listdir(folderPath) pathsList = {} # A dictionary mapping the name of a file to its complete path for file in filesList: pathsList.update( {file[:-4] : folderPath+file} ) for songName in pathsList.keys(): song = eyed3.load(pathsList[songName]) metadata = getData(songName) try: song.tag.title = metadata[0] song.tag.artist = metadata[1] song.tag.album = metadata[2] #song.tag.lyrics = metadata[3] # ^ This tag doesn't seem to work. Might be something to do with lyrics being a formatted string. song.tag.save() os.rename(pathsList[songName], folderPath+song.tag.artist+' - '+song.tag.title+'.mp3') print("Updated '{0}'.".format(song.tag.artist+' - '+song.tag.title)) except TypeError: print("No metadata found for '{0}'. Skipping it.".format(songName)) except AttributeError: print("'{0}' is not an mp3 file. Skipping it.".format(songName))
def set_tags(path, info): ## todo: do smth with crashes mp3 = eyed3.load(path) mp3.tag.artist = info['artist'] # mp3.tag.album = info['album'] mp3.tag.title = info['title'] mp3.tag.save()
def create_from_mp3_path(cls, mp3_path): """Given a path to an mp3, returns a Song object""" import eyed3 mp3_path = os.path.abspath(mp3_path) audio_file = eyed3.load(mp3_path) return cls.create_from_eyed3_file(audio_file)
def set_song_info(filename, info): audio = eyed3.load(filename) audio.tag.title = info[u'title'] audio.tag.album = info[u'album'] audio.tag.artist = info[u'artist'] audio.tag.track_num = info[u'track_num'] audio.tag.save()
def changeNoneArtistAndCreateFolders(defaultFolder, artistDefault): for arquivo in glob.glob(defaultFolder+'*.mp3'): audio = eyed3.load(arquivo) if audio is None: raise Error(arquivo + " Is not valid!!!") continue if audio.tag is None: audio.tag = eyed3.id3.Tag() audio.tag.file_info = eyed3.id3.FileInfo("foo.id3") print(arquivo + " as a invalid Tag!!!") if audio.tag.artist is None: audio.tag.artist=unicode(artistDefault, "UTF-8") audio.tag.save() if(options.verbose): print("Artist Name is changed to "+artistDefault+" in Arquive "+ os.path.basename(arquivo)+"!") folder=defaultFolder+str(audio.tag.artist) if not os.path.exists(folder): os.makedirs(folder) if(options.verbose): print("Create folder artist "+ folder) os.rename(arquivo, folder+'/'+os.path.basename(arquivo)) if(options.verbose): print("Arquive "+ os.path.basename(arquivo)+ " Changed!") print("All arquives are Update!")
def testNewTagAll(self, version=id3.ID3_DEFAULT_VERSION): self.testNewTagArtist(version) self.testNewTagAlbum(version) self.testNewTagTitle(version) self.testNewTagTrackNum(version) self.testNewTagTrackTotal(version) self.testNewTagGenre(version) self.testNewTagYear(version) self.testNewTagSimpleComment(version) af = eyed3.load(self.test_file) assert (af.tag.artist == "The Cramps") assert (af.tag.album == "Psychedelic Jungle") assert (af.tag.title == "Green Door") assert (af.tag.track_num == (14, 14 if version[0] != 1 else None)) assert ((af.tag.genre.name, af.tag.genre.id) == ("Rock", 17)) if version == id3.ID3_V2_3: assert (af.tag.original_release_date.year == 1981) else: assert (af.tag.release_date.year == 1981) if version[0] != 1: assert (af.tag.comments[0].text == "Starlette") assert (af.tag.comments[0].description == "") assert (af.tag.version == version)
def apply_path(self,path,base_path): self.base_path = base_path if isfile(path): mp3 = eyed3.load(path) self.path = path if mp3.tag: self.artist = mp3.tag.artist self.album = mp3.tag.album self.title = mp3.tag.title self.track_num, self.total_tracks = mp3.tag.track_num if not self.track_num: self.total_tracks = None self.disc_num, self.total_discs = mp3.tag.disc_num if not self.total_discs: self.total_discs = 1 if not self.disc_num: self.disc_num = 1 self.publisher = mp3.tag.publisher if not self.publisher: self.publisher = '(Unknown)' if mp3.tag.best_release_date: self.year = str(mp3.tag.best_release_date) if not self.year: self.year = '' if mp3.tag.genre: self.genre = mp3.tag.genre.name
def get_music_metadata(file): with open(os.path.join(temp_upload_path,file.name),'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) meta = {} music = eyed3.load(os.path.join(temp_upload_path,file.name)) if music: if music.tag: meta['title'] = music.tag.title meta['author'] = music.tag.artist meta['album'] = music.tag.album if not meta['title']: meta['title'] = file.name.split('.')[0] if len(music.tag.images) > 0: meta['image'] = bytearray(music.tag.images[0].image_data) else: meta['title'] = file.name.split('.')[0] meta['author'] = None meta['album'] = None os.remove(os.path.join(temp_upload_path,file.name)) return meta
def _test_file(pth): errors = [] info = os.path.splitext(os.path.basename(pth))[0].split(' ') fil = eyed3.load(pth) tests = [ ('mpeg_version', Decimal(str(fil.info.mp3_header.version)), Decimal(info[0][-3:])), ('sample_freq', Decimal(str(fil.info.mp3_header.sample_freq))/1000, Decimal(info[1][:-3])), ('vbr', fil.info.bit_rate[0], bool(info[2] == '__vbr__')), ('stereo_mode', fil.info.mode, _translate_mode(info[3])), ('duration', round(fil.info.time_secs), 10), ] if info[2] != '__vbr__': tests.append(('bit_rate', fil.info.bit_rate[1], int(info[2][:-4]))) for test, reported, expected in tests: (passed, msg) = _do_test(reported, expected) if not passed: errors.append("%s: %s" % (test, msg)) print("%s: %s" % (os.path.basename(pth), 'FAIL' if errors else 'ok')) for err in errors: print(" %s" % err) return errors
def main(): if len(sys.argv) <= 3: usage() sys.exit(2) mtp = pymtp.MTP() mtp.connect() source = sys.argv[1] target = sys.argv[2] parent = int(sys.argv[3]) id3data = eyed3.load(source).tag metadata = pymtp.LIBMTP_Track() if hasattr(id3data, 'artist'): metadata.artist = id3data.artist if hasattr(id3data, 'title'): metadata.title = id3data.title if hasattr(id3data, 'album'): metadata.album = id3data.album track_id = mtp.send_track_from_file(source, target, metadata, parent) print "Created new track with ID: %s" % (track_id) mtp.disconnect()
def get_metadata(filepath): # todo: read config file for track metadata # and related info. trackfile = eyed3.load(filepath) return (trackfile.tag.artist, trackfile.tag.title, trackfile.tag.album)
def __init__(self,folder): self.folder = folder print("Looking for images and songs in %s:" % folder) jpgs = glob.glob(os.path.join(folder,"*.jpg")) pngs = glob.glob(os.path.join(folder,"*.png")) bmps = glob.glob(os.path.join(folder,"*.bmp")) bmps = glob.glob(os.path.join(folder,"*.gif")) self.images = jpgs + pngs + bmps song_formats = ["mp3"]#"m4a","mp3","flv","ogg","wav"] self.songs = [] self.song_durations = {} for song_format in song_formats: files = glob.glob(os.path.join(folder,"*.%s" % song_format)) for f in files: audiofile = eyed3.load(f) self.song_durations[f] = audiofile.info.time_secs self.songs += files # sort songs and images self.songs = sorted(self.songs) self.images = sorted(self.images) print("found image files: %s" % [ os.path.basename(i) for i in self.images]) print("found song files: %s" % [ os.path.basename(s) for s in self.songs]) if len(self.images) == 0: raise RuntimeError("Ach! No images found in %s, so this \ is an invalid slideshow program segment." % folder) self.img_idx = 0 self.song_idx = 0
def main(): try: filename = parce_path(sys.argv[1]) # arg 1 sould be filename art = parce_path(sys.argv[2]) # arg 2 will be the picture to add except IndexError: help_page() return 3 while check_file(filename): in_put = raw_input("Enter valid file path for mp3: ") filename = parce_path(in_put) # convert to acceptable path while check_file(art): in_put = raw_input("Enter valid path to art: ") art = parce_path(in_put) while ".mp3" not in filename: print("Song must be of format .jpg") in_put = raw_input("Enter a .mp3 file: ") filename = parce_path(in_put) while ".jpg" not in art: # if file not .jpg ask for .jpg print("Art must be of format .jpg") in_put = raw_input("Enter a .jpg file: ") art = parce_path(in_put) imagedata = open(art, "rb").read() # open image audiofile = eyed3.load(filename) # load image into eyed3 audiofile.tag.images.set(3, imagedata, "image/jpeg", u" ") audiofile.tag.save() print("\n\nAdded {} to {} as album conver!\n".format(art, filename))
def get_eps(self): afs = [] for m in [x for x in os.listdir(self.mp3_path) if 'mp3' in x.lower()]: af = eyed3.load('%s/%s' % (self.mp3_path, m)) if af.tag.title != '': afs.append(af) return sorted([(x.tag.title, {'title':x.tag.title, 'filename':x.path, 'audiofile':x}) for x in afs], reverse=True)
def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False): ''' This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used. ARGUMENTS: - dirName: the path of the folder where the MP3s are stored - Fs: the sampling rate of the generated WAV files - nC: the number of channesl of the generated WAV files - useMp3TagsAsName: True if the WAV filename is generated on MP3 tags ''' types = (dirName+os.sep+'*.mp3',) # the tuple of file types filesToProcess = [] for files in types: filesToProcess.extend(glob.glob(files)) for f in filesToProcess: #tag.link(f) audioFile = eyed3.load(f) if useMp3TagsAsName and audioFile.tag != None: artist = audioFile.tag.artist title = audioFile.tag.title if artist!=None and title!=None: if len(title)>0 and len(artist)>0: wavFileName = ntpath.split(f)[0] + os.sep + artist.replace(","," ") + " --- " + title.replace(","," ") + ".wav" else: wavFileName = f.replace(".mp3",".wav") else: wavFileName = f.replace(".mp3",".wav") else: wavFileName = f.replace(".mp3",".wav") command = "avconv -i \"" + f + "\" -ar " +str(Fs) + " -ac " + str(nC) + " \"" + wavFileName + "\""; print command os.system(command.decode('unicode_escape').encode('ascii','ignore').replace("\0",""))
def changefilename(song): #module to change the filename of the mp3 when it's finished downloding. Earmilk uses a strange filenaming convention os.chdir(Music_dir) audiofile = eyed3.load(song) print audiofile.tag.artist print audiofile.tag.title newname = str(audiofile.tag.title) + ".mp3" os.rename(song,newname)
def __init__(self, songLoc): """ Parses a songfile for the artist and title ID3 tags and creates the theoretical path for the songfile's samplepage. Param: The directory path to a song file, as a string. Throws: MissingTagException if tag(s) could not be found. """ songfile = eyed3.load(songLoc) try: self.whoSampledHTML = None self.artistName = songfile.tag.artist self.songTitle = songfile.tag.title self.sampleJSON = {} if self.artistName == None or self.songTitle == None: raise MissingTagException() except MissingTagException: print "audiofile at " + songLoc + " has missing tag information" self.whoSampledPath = ("/" + self.artistName + "/" + \ self.songTitle + "/").replace(" ", "-") self.sampleJSON[self.whoSampledPath] = { self.SONGS_SAMPLED_CALL:{}, \ self.WHO_SAMPLED_CALL: {} }
def uploadToEcho(filenames): retry=[] successTracks = [] i=0 if not os.path.isdir('echoNestUploads'): os.mkdir('echoNestUploads') for f in filenames: time = t.localtime() time = str(time.tm_hour) +'_' + str(time.tm_min) + '_' + str(time.tm_sec) try: print 'uploading...', f rTrack = track.track_from_file(open(f, 'r'), 'mp3') if rTrack: print rTrack.tempo print rTrack.time_signature print 'gather track info' trackInfo = [f, rTrack.tempo, rTrack.time_signature, rTrack.id] successTracks.append(trackInfo) pickle.dump(trackInfo, open('echoNestUploads/'+str(i)+'-'+time+'.pkl', 'w')) try: print 'saving id3' tag = d3.load(f).tag tag.bpm = rTrack.tempo tag.copyright_url = 'echo' except: print 'id3 failed' except: print "couldn't upload" retry.append(f) i+=1 return successTracks, retry
def library_scan(path): print("Scanning " + path) count = 0 tree = lambda: collections.defaultdict(tree) musiclibrary = tree() for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, '*.mp3'): filepath = os.path.join(root, filename) try: audiofile = eyed3.load(filepath) try: artist=audiofile.tag.artist except AttributeError: artist="" try: album=audiofile.tag.album except AttributeError: album="" try: title=audiofile.tag.title except AttributeError: title="" musiclibrary[artist][album][title]=filepath count += 1 except Exception, e: print("Error loading " + filepath) print(e)
def GetDuration(clip): if '.mp4' in str(clip): return VideoFileClip(clip).duration elif '.mp3' in str(clip): return eyed3.load('{}'.format(clip)).info.time_secs
def trackinfo(x): af = eyed3.load('path/to/song (%d).mp3' % int(x)) return af.tag.title +' '+'by ' + af.tag.artist +', Year: '+ str(af.tag.getBestDate())
def update_library(): lib = [] print(os.listdir(app.config['MUSIC_DIR'])) for (path, dirs, files) in os.walk(app.config['MUSIC_DIR']): for f in files: if f.endswith(".mp3"): abs_path = os.path.join(path, f) print("Abs: " + abs_path) rel_path = abs_path[len(app.config['MUSIC_DIR']) + 1:] db_song = g.db.execute( u"select id, last_update from song where path=?", [rel_path]).fetchone() if not db_song: print(abs_path) print("New song: " + rel_path) data = eyed3.load(abs_path) lib.append({ 'id': -1, 'artist': data.tag.artist, 'title': data.tag.title, 'album': data.tag.album, 'filename': rel_path }) else: if db_song[1] < os.path.getmtime(abs_path): print("Update song: " + rel_path) data = eyed3.load(abs_path) lib.append({ 'id': db_song[0], 'artist': data.tag.artist, 'title': data.tag.title, 'album': data.tag.album, 'filename': rel_path }) count_new = 0 count_update = 0 for song in lib: db_artist = g.db.execute(u"select id from artist where name=?", [song['artist']]).fetchone() artist_id = -1 if db_artist: artist_id = db_artist[0] else: cur = g.db.execute(u"insert into artist (name) values (?)", [song['artist']]) artist_id = cur.lastrowid db_album = g.db.execute(u"select id from album where name=?", [song['album']]).fetchone() album_id = -1 if db_album: album_id = db_album[0] else: cur = g.db.execute( u"insert into album (artist_id, name) values (?, ?)", [artist_id, song['album']]) album_id = cur.lastrowid if song['id'] == -1: g.db.execute( u"insert into song (name, artist_id, album_id, path, last_update) values (?, ?, ?, ?, ?)", [ song['title'], artist_id, album_id, song['filename'], time.time() ]) count_new += 1 else: g.db.execute( u"update song set name=?, artist_id=?, album_id=?, path=?, last_update=? where id=?", [ song['title'], artist_id, album_id, song['filename'], time.time(), song['id'] ]) count_update += 1 g.db.commit() return (count_new, count_update)
def set_mp3_meta_data(audio_obj, mp3_path): """Sets the meta data on the mp3 file to good values. :param audio_obj: an Audio object to clean up. :param mp3_path: the path to the mp3 to be converted. """ court = audio_obj.docket.court # Load the file, delete the old tags and create a new one. audio_file = eyed3.load(mp3_path) # Undocumented API from eyed3.plugins.classic.ClassicPlugin#handleRemoves id3.Tag.remove( audio_file.tag.file_info.name, id3.ID3_ANY_VERSION, preserve_file_time=False, ) audio_file.initTag() audio_file.tag.title = best_case_name(audio_obj) audio_file.tag.album = u'{court}, {year}'.format( court=court.full_name, year=audio_obj.docket.date_argued.year ) audio_file.tag.artist = court.full_name audio_file.tag.artist_url = court.url audio_file.tag.audio_source_url = audio_obj.download_url audio_file.tag.comments.set( u'Argued: {date_argued}. Docket number: {docket_number}'.format( date_argued=audio_obj.docket.date_argued.strftime('%Y-%m-%d'), docket_number=audio_obj.docket.docket_number, )) audio_file.tag.genre = u'Speech' audio_file.tag.publisher = u'Free Law Project' audio_file.tag.publisher_url = u'https://free.law' audio_file.tag.recording_date = audio_obj.docket.date_argued.strftime('%Y-%m-%d') # Add images to the mp3. If it has a seal, use that for the Front Cover # and use the FLP logo for the Publisher Logo. If it lacks a seal, use the # Publisher logo for both the front cover and the Publisher logo. try: has_seal = seals_data[court.pk]['has_seal'] except AttributeError: # Unknown court in Seal Rookery. has_seal = False except KeyError: # Unknown court altogether (perhaps a test?) has_seal = False flp_image_frames = [ 3, # "Front Cover". Complete list at eyed3/id3/frames.py 14, # "Publisher logo". ] if has_seal: with open(os.path.join(seals_root, '512', '%s.png' % court.pk), 'r') as f: audio_file.tag.images.set( 3, f.read(), 'image/png', u'Seal for %s' % court.short_name, ) flp_image_frames.remove(3) for frame in flp_image_frames: with open(os.path.join(settings.INSTALL_ROOT, 'cl', 'audio', 'static', 'png', 'producer-300x300.png'), 'r') as f: audio_file.tag.images.set( frame, f.read(), 'image/png', u'Created for the public domain by Free Law Project', ) audio_file.tag.save()
# -*- coding: cp1252 -*- import eyed3 import eyed3.id3 import re import glob import os import shutil mp3_path = "C:\Users\Julia\Music\iTunes Music\Sjöwall_Wahlöö\Mannen som gick upp i rök" os.chdir(mp3_path) files = os.listdir(os.curdir) for mp3file in files: if mp3file.endswith('06 006-Mannen som gick upp i rök.mp3'): audiofile = eyed3.load(mp3file, (2, None, None)) print audiofile.tag.album #old_title = audiofile.tag.title #new_title = old_title.replace('_','-') #print new_title #audiofile.tag.title = new_title #audiofile.tag.artist = u'Sjöwall/Wahlöö' audiofile.tag.album = u'Mannen som gick upp i rök' audiofile.tag.save() print audiofile.tag.artist
import pygame file = r'D:\CC++C#Code\github\python\code\PythonTest\baidu-aip\auido.mp3' pygame.mixer.init() # 语速失真 print("播放音乐1") track = pygame.mixer.music.load(file) pygame.mixer.music.play() time.sleep(10) pygame.mixer.music.stop() #import os #os.system('auido.mp3') #语速正常,缺点,弹出播放器窗口,打开完成后不占用进程 ''' def playmusic(path): clip = mp3play.load(path) clip.play() time.sleep(10) clip.stop() playmusic('auido.mp3') ''' import eyed3 audiofile = eyed3.load("auido.mp3") #audiofile.tag.artist = u"Nobunny" #audiofile.tag.album = u"Love Visions" #audiofile.tag.album_artist = u"Various Artists" #audiofile.tag.title = u"I Am a Girlfriend" #audiofile.tag.track_num = 4 #audiofile.tag.save() #audiofile.
import eyed3 from operator import itemgetter import datetime import regex as re from xpinyin import Pinyin p = Pinyin() audiodir = "./websites/slow-chinese.com/podcasts/" externaltextdir = "./websites/external_transcripts/" targetdir = "../_posts/" for dirpath, dnames, fnames in os.walk(audiodir): for fname in fnames: if ".mp3" in fname and "Reading_China" in fname: song = eyed3.load(os.path.join(dirpath, fname)) title = song.tag.title author = song.tag.artist date = song.tag.recording_date episode_num = int(fname[-6:-4]) if title is None: title = str(episode_num) title = title.replace(":", " -") title = title.split("#")[-1] fnametitle = re.sub(r"\d+", "", title).replace(" ", "") outfname = p.get_pinyin(re.sub(r"\p{P}+", "", fnametitle)) + ".md" outfname = p.get_pinyin("中文天天读") + "-{:03d}-".format(episode_num) + outfname outfname = outfname.lower()
async def ns(context): await context.edit("获取中 . . .") status = False for _ in range(20): # 最多尝试20次 req = requests.get( "http://api.uomg.com/api/rand.music?sort=%E7%83%AD%E6%AD%8C%E6%A6%9C&format=json" ) if req.status_code == 200: req = json.loads(req.content) try: songid = req["data"]["url"][45:] music = req['data']['url'] except KeyError: continue headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ' 'like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063', "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng," "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" } music = requests.request("GET", music, headers=headers) name = str(req['data']['name']) + ".mp3" with open(name, 'wb') as f: f.write(music.content) if (path.getsize(name) / 1024) < 100: remove(name) continue req = requests.get( "https://api.imjad.cn/cloudmusic/?type=detail&id=" + songid) if req.status_code == 200: req = json.loads(req.content) album = req['songs'][0]['al']['name'] albumpic = requests.get(req['songs'][0]['al']['picUrl']) artist = req['songs'][0]['ar'][0]['name'] title = req['songs'][0]['name'] cap = artist + " - " + title else: continue tag = eyed3.load(name).tag tag.encoding = '\x01' tag.artist = artist tag.title = title tag.album = album tag.images.set(3, albumpic.content, "image/jpeg", u'') tag.save() await context.client.send_file(context.chat_id, name, caption=cap, link_preview=False, force_document=False) try: remove(name) except: pass status = True break else: continue if not status: await context.edit("出错了呜呜呜 ~ 试了好多好多次都无法访问到 API 服务器 。") sleep(2) await context.delete()
def set_mp3_meta_data(audio_obj, mp3_path): """Sets the meta data on the mp3 file to good values. :param audio_obj: an Audio object to clean up. :param mp3_path: the path to the mp3 to be converted. """ court = audio_obj.docket.court # Nuke the old id3 tags. eyed3_command = [ 'eyeD3', '--remove-all', '--quiet', mp3_path, ] _ = subprocess.check_output(eyed3_command, stderr=subprocess.STDOUT) # Load the file, then create a fresh tag. audio_file = eyed3.load(mp3_path) audio_file.initTag() audio_file.tag.title = audio_obj.case_name audio_file.tag.album = u'{court}, {year}'.format( court=court.full_name, year=audio_obj.date_argued.year ) audio_file.tag.artist = court.full_name audio_file.tag.artist_url = court.url audio_file.tag.audio_source_url = audio_obj.download_url audio_file.tag.comments.set( u'Argued: {date_argued}. Docket number: {docket_number}'.format( date_argued=audio_obj.date_argued.strftime('%Y-%m-%d'), docket_number=audio_obj.docket_number, )) audio_file.tag.genre = u'Speech' audio_file.tag.publisher = u'Free Law Project' audio_file.tag.publisher_url = u'http://www.freelawproject.org' audio_file.tag.recording_date = audio_obj.date_argued.strftime('%Y-%m-%d') # Add images to the mp3. If it has a seal, use that for the Front Cover # and use the FLP logo for the Publisher Logo. If it lacks a seal, use the # Publisher logo for both the front cover and the Publisher logo. try: has_seal = seals_data[court.pk]['has_seal'] except AttributeError: # Unknown court in Seal Rookery. has_seal = False except KeyError: # Unknown court altogether (perhaps a test?) has_seal = False flp_image_frames = [ 3, # "Front Cover". Complete list at eyed3/id3/frames.py 14, # "Publisher logo". ] if has_seal: with open(os.path.join(seals_root, '512', '%s.png' % court.pk), 'r') as f: audio_file.tag.images.set( 3, f.read(), 'image/png', u'Seal for %s' % court.short_name, ) flp_image_frames.remove(3) for frame in flp_image_frames: with open(os.path.join(settings.INSTALL_ROOT, 'alert', 'audio', 'static', 'png', 'producer.png'), 'r') as f: audio_file.tag.images.set( frame, f.read(), 'image/png', u'Created for the public domain by Free Law Project', ) audio_file.tag.save()
'-ar', '22050', '-ab', '48k', path_to_tmp_location] try: output = subprocess.check_output(avconv_command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError, e: print 'avconv failed command: %s\nerror code: %s\noutput: %s\n' % \ (avconv_command, e.returncode, e.output) print traceback.format_exc() raise # Have to do this last because otherwise the mp3 hasn't yet been generated. file_name = trunc(audio_file.case_name.lower(), 72) + '_cl.mp3' set_mp3_meta_data(audio_file, path_to_tmp_location) audio_file.duration = eyed3.load(path_to_tmp_location).info.time_secs with open(path_to_tmp_location, 'r') as mp3: try: cf = ContentFile(mp3.read()) audio_file.local_path_mp3.save(file_name, cf, save=False) except: msg = "Unable to save mp3 to audio_file in scraper.tasks.process_" \ "audio_file for item: %s\nTraceback:\n%s" % \ (audio_file.pk, traceback.format_exc()) ErrorLog(log_level='CRITICAL', court=audio_file.docket.court, message=msg).save() audio_file.processing_complete = True audio_file.save() os.remove(path_to_tmp_location)
import os import re import eyed3 source_dir = r'C:\Users\greg\Downloads\The First Law Trilogy\The First Law 03 Last Argument Of Kings' dest_dir = r'C:\Users\greg\Downloads\The First Law Trilogy\1' image = r'C:\Users\greg\Downloads\Audiobooks\Legends\1 Old Republic Era (2,500 to 800 BBY)\2 - The Old Republic Revan\Star Wars The Old Republic Revan.jpg' i = 1 for subdir, dirs, files in os.walk(source_dir): for file in files: if not file.endswith("mp3"): continue old_path = os.path.join(subdir, file) # disc_num = int(re.search(r"(?:Disc )(\d+)", subdir).group(1)) # track_num = int(re.search(r"(?:Track )(\d+)", file).group(1)) audio_file = eyed3.load(old_path) # audio_file.tag.title = f"Revan Track{i:03}" # audio_file.tag.album = "The Old Republic Revan" # audio_file.tag.artist = "Drew Karpyshyn" audio_file.tag.track_num = i #audio_file.tag.images.set(3, open(image, 'rb').read(), 'image/jpeg') audio_file.tag.save() # new_path = os.path.join(dest_dir, f"Revan_Track{i:03}.mp3") # os.rename(old_path, new_path) # print(new_path) i += 1
import eyed3 from shutil import copy desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') os.chdir(desktop) src = os.path.join(os.getcwd(), 'Music') dst = os.path.join(os.getcwd(), 'NewMusic') count = 0 for subdir, dirs, files in os.walk(src): for file in files: songPath = os.path.join(subdir, file) print(songPath) song = eyed3.load(songPath) artist = song.tag.album_artist album = song.tag.album artistFolder = os.path.join(dst, artist) albumFolder = os.path.join(artistFolder, album) if not (os.path.exists(artistFolder) ): #if the artist folder does not exist, create os.makedirs(artistFolder) if not (os.path.exists(albumFolder) ): #if the album folder does not exist, create os.makedirs(albumFolder) newSongPath = os.path.join(albumFolder, file) if not (os.path.exists(newSongPath) ): #if the song does not exist, copy
def __init__(self, path = '', artist = ''): ''' @params: path : can be either a folder or a music but needs to end with ".mp3". artist: the artist of the music. ''' os.chdir(defaultPath) if path: path = os.path.normpath(path) path = path[path.startswith('\\'):].strip() self.path = path else: self.path = defaultPath self.title = '' ## No .mp3 at the end self.artist = artist self.format = '.mp3' self.lyrics = '' self.lyrics_list = [] self.song_list = [] self.success_list = [] self.fail_list = [] self.again_list = [] self.talf = () ## title artist lyrics format if os.path.exists(self.path): if os.path.isdir(self.path): os.chdir(self.path) elif os.path.isfile(self.path) and is_music(self.path): self.title = get_title(os.path.basename(self.path)) self.format = find_fmt(self.path) self.path = os.path.dirname(self.path) else: self.title = get_title(os.path.basename(self.path)) self.path = os.path.dirname(self.path) or defaultPath ## 忘记文件格式 for fmt in music_fmt: full_path = path + fmt if os.path.isfile(full_path): music = eyed3.load(full_path) self.artist = music.tag.artist self.format = fmt self.lyrics = music.tag.lyrics[-1].text break else: ## 模糊查找相似歌曲,不支持模糊查找路径 assert os.path.exists(self.path), '路径不存在哦' os.chdir(self.path) most_similar = ('', 0, '') ## song, score, artist for song in os.listdir(): if not is_music(song): continue score = similar(song, self.title) music_artist = eyed3.load(song).tag.artist if artist: bonus = similar(music_artist, artist) score += bonus if score != 0 and score >= most_similar[1]: most_similar = (song, score, music_artist) song, score, self.artist = most_similar de = '的' if self.artist else '' text = f'{self.artist}{de}《{song}》' if score: self.title = get_title(song) self.format = find_fmt(song) print(f'这个路径下只能找到{text}哦,自动调整成这首歌啦') else: raise FileNotFoundError(f'QAQ这个路径下找不到{text}诶...') self.is_file = self.title != '' if not path.startswith(defaultPath) and os.path.exists(defaultPath + self.path): self.path = defaultPath + self.path if not self.path.endswith('\\'): self.path += '\\' if self.is_file: music = eyed3.load(self.path + self.title + self.format) self.artist = music.tag.artist try: self.lyrics = music.tag.lyrics[-1].text self.lyrics_list.append(self.lyrics) except IndexError: pass else: for song in os.listdir(self.path): if is_music(song): self.song_list.append(song) try: self.lyrics_list.append(eyed3.load(song).tag.lyrics[-1].text) except IndexError: pass songs = len(self.song_list) if songs == 0: raise FileNotFoundError('噫,这个文件夹好像没有音乐呢……') elif songs == 1: song = self.song_list[0] music = eyed3.load(song) self.title = get_title(song) self.artist = music.tag.artist self.format = find_fmt(song) try: self.lyrics = self.lyrics_list[0] except IndexError: pass
def set_tags(self): song = eyed3.load(self.local_filename) song.initTag() song.tag.artist = "Mike Krahulik and Jerry Holkins" song.tag.album = "Downloadable Content, The Penny Arcade Podcast" song.tag.save()
async def nem(context): proxies = {} proxynum = 0 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063', "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "X-Real-IP": "223.252.199.66"} proxy = [{'http': 'http://192.210.137.108:8080', 'https': 'http://192.210.137.108:8080'}, {'http': 'http://music.lolico.me:39000', 'https': 'http://music.lolico.me:39000'}, {'http': 'http://aimer.one:2333', 'https': 'http://aimer.one:2333'}, {'http': 'http://fs2.ilogic.net.cn:5200', 'https': 'http://fs2.ilogic.net.cn:5200'}, {'http': 'http://64.64.250.246:8080', 'https': 'http://64.64.250.246:8080'}] helptext = "**使用方法:** `-nem` `<指令>` `<关键词>`\n\n指令s为搜索,p为点歌,id为歌曲ID点歌,r为随机热歌(无关键词)\n搜索在s后添加数字如`-nem` `s8` `<关键词>`调整结果数量\n搜索灰色歌曲请尽量**指定歌手**\n可回复搜索结果消息`-nem` `p` `<歌曲数字序号>`点歌" apifailtext = "出错了呜呜呜 ~ 试了好多好多次都无法访问到 API 服务器 。" if len(context.parameter) < 2: if len(context.parameter) == 0: await context.edit(helptext) return elif context.parameter[0] == "r": # 随机热歌 await context.edit("随机中 . . .") for _ in range(20): # 最多重试20次 apinum = random.randint(0, 1) apitype = random.randint(0, 1) if apitype == 0: apitype = "飙升榜" else: apitype = "热歌榜" if apinum == 0: url = "https://api.vvhan.com/api/rand.music?type=json&sort=" + apitype else: url = "https://api.uomg.com/api/rand.music?sort=" + apitype + "&format=json" status = False try: randsong = requests.get(url, headers=headers) if randsong.status_code == 200: randsong = json.loads(randsong.content) if apinum == 0 and randsong['success'] is True: context.parameter[0] = "id" context.parameter.append( str(randsong['info']['id'])) status = True break elif apinum == 1 and randsong['code'] == 1: context.parameter[0] = "id" context.parameter.append( str(randsong['data']['url'][45:])) status = True break except: continue if status is False: await context.edit(apifailtext) sleep(3) await context.delete() return else: # 错误输入 await context.edit(helptext) return # 整理关键词 keyword = '' for i in range(1, len(context.parameter)): keyword += context.parameter[i] + " " keyword = keyword[:-1] idplay = False if context.parameter[0] == "id": # ID点歌功能 if len(context.parameter) > 2: await context.edit(helptext) return idplay = keyword context.parameter[0] = "p" if context.parameter[0][0] == "s": # 搜索功能 await context.edit(f"【{keyword}】搜索中 . . .") if len(context.parameter[0]) > 1: limit = str(context.parameter[0][1:]) else: limit = "5" url = "http://music.163.com/api/search/pc?&s=" + \ keyword + "&offset=0&limit=" + limit + "&type=1" for _ in range(20): # 最多尝试20次 status = False req = requests.request("GET", url, headers=headers) if req.status_code == 200: req = json.loads(req.content) if req['code'] == 200: result = req['result'] if req['result']['songCount'] == 0: result = False else: result = False if result: info = defaultdict() for i in range(len(req['result']['songs'])): info[i] = {'id': '', 'title': '', 'alias': '', 'album': '', 'albumpic': '', 'artist': ''} info[i]['id'] = req['result']['songs'][i]['id'] info[i]['title'] = req['result']['songs'][i]['name'] info[i]['alias'] = req['result']['songs'][i]['alias'] info[i]['album'] = req['result']['songs'][i]['album']['name'] info[i]['albumpic'] = req['result']['songs'][i]['album']['picUrl'] for j in range(len(req['result']['songs'][i]['artists'])): info[i]['artist'] += req['result']['songs'][i]['artists'][j]['name'] + " " text = f"<strong>关于【{keyword}】的结果如下</strong> \n" for i in range(len(info)): text += f"#{i+1}: \n<strong>歌名</strong>: {info[i]['title']}\n" if info[i]['alias']: text += f"<strong>别名</strong>: <i>{info[i]['alias'][0]}</i>\n" if info[i]['album']: res = '<a href="' + \ info[i]['albumpic'] + '">' + \ info[i]['album'] + '</a>' text += f"<strong>专辑</strong>: {res} \n" text += f"<strong>作者</strong>: {info[i]['artist']}\n<strong>歌曲ID</strong>: <code>{info[i]['id']}</code>\n————————\n" text += "\n<strong>回复此消息</strong><code>-nem p <歌曲序号></code><strong>即可点歌</strong>" await context.edit(text, parse_mode='html', link_preview=True) status = True break else: await context.edit("**未搜索到结果**") sleep(3) await context.delete() status = True break else: continue if status is False: await context.edit(apifailtext) sleep(3) await context.delete() return elif context.parameter[0] == "p": # 点歌功能 try: reply = await context.get_reply_message() except ValueError: await context.edit("出错了呜呜呜 ~ 无效的参数。") return search = "" title = "" if reply: msg = reply.message search = re.findall(".*【(.*)】.*", msg) if search: try: start = "#" + context.parameter[1] + ":" search = ".*" + start + "(.*?)" + '————————' + ".*" msg = re.findall(search, msg, re.S)[0] search = ".*歌曲ID: (.*)\n.*" title = ".*歌名: (.*?)\n.*" title = "【"+re.findall(title, msg, re.S)[0]+"】" idplay = re.findall(search, msg, re.S)[0] if reply.sender.is_self: await reply.edit(f"{title}点歌完成") except: await context.edit("出错了呜呜呜 ~ 无效的歌曲序号。") return else: await context.edit("出错了呜呜呜 ~ 无效的参数。") return await context.edit("获取中 . . .") try: import eyed3 imported = True except ImportError: imported = False await bot.send_message(context.chat_id, '(`eyeD3`支持库未安装,歌曲文件信息将无法导入\n请使用 `-sh` `pip3` `install` `eyed3` 安装,或自行ssh安装)') url = "http://music.163.com/api/search/pc?&s=" + \ keyword + "&offset=0&limit=1&type=1" for _ in range(20): # 最多尝试20次 status = False if proxynum > (len(proxy) - 1): # 代理自动切换至下一个 proxynum = 0 proxies = proxy[proxynum] proxynum += 1 if idplay: # 指定ID播放 url = "http://music.163.com/api/song/detail?id=" + \ idplay + "&ids=[" + idplay + "]" # 搜索后播放 req = requests.request("GET", url, headers=headers) if req.status_code == 200: req = json.loads(req.content) if req['code'] == 200: if idplay: req['result'] = req result = req['result'] if not idplay: if req['result']['songCount'] == 0: result = False else: result = False if result: info = {'id': '', 'title': '', 'alias': '', 'album': '', 'albumpic': '', 'artist': '', 'br': ''} info['id'] = req['result']['songs'][0]['id'] info['title'] = req['result']['songs'][0]['name'] info['alias'] = req['result']['songs'][0]['alias'] info['album'] = req['result']['songs'][0]['album']['name'] info['albumpic'] = req['result']['songs'][0]['album']['picUrl'] if req['result']['songs'][0]['hMusic']: info['br'] = req['result']['songs'][0]['hMusic']['bitrate'] elif req['result']['songs'][0]['mMusic']: info['br'] = req['result']['songs'][0]['mMusic']['bitrate'] elif req['result']['songs'][0]['lMusic']: info['br'] = req['result']['songs'][0]['lMusic']['bitrate'] for j in range(len(req['result']['songs'][0]['artists'])): info['artist'] += req['result']['songs'][0]['artists'][j]['name'] + "; " info['artist'] = info['artist'][:-2] if title: title = "" else: title = f"【{info['title']}】" await context.edit(f"{title}下载中 . . .") try: from Crypto.Cipher import AES AES.new("0CoJUm6Qyw8W8jud".encode('utf-8'), AES.MODE_CBC, "0102030405060708".encode('utf-8')) ccimported = True except ImportError: ccimported = False await bot.send_message(context.chat_id, '(`PyCryptodome`支持库未安装,音乐曲库/音质受限\n请使用 `-sh` `pip3` `install` `pycryptodome` 安装,或自行ssh安装)') name = info['title'].replace('/', " ") + ".mp3" name = name.encode('utf-8').decode('utf-8') if ccimported: # 尝试使用高清音质下载 songid = str(info['id']) class WangyiyunDownload(object): def __init__(self): self.key = '0CoJUm6Qyw8W8jud' self.public_key = "010001" self.modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7' # 偏移量 self.iv = "0102030405060708" # 请求头 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36', # 传入登录cookie, 'Cookie': 'MUSIC_U=f52f220df171da480dbf33ce89947961585a7fdf08c89a2a4bdd6efebd86544233a649814e309366;', "X-Real-IP": "223.252.199.66", } # 请求url self.url = 'https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token=' # 生成16位随机数字符串 def set_random_num(self): random_num = '' # 随机取16个字符 string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" for ___ in range(16): n = math.floor( random.uniform(0, 1) * len(string)) random_num += string[n] # 返回16位随机数字符串 return random_num # 生成encSecKey # 通过public_key和modulus对random_num进行RSA加密 def RSA_encrypt(self, random_num): # 将16位随机数字符串倒序并以utf-8编码 random_num = random_num[::-1].encode('utf-8') # 将其以hex(16进制)编码 random_num = codecs.encode( random_num, 'hex_codec') # 加密(三者均要从16进制转换为10进制) # int(n, 16) --> 将16进制字符串n转换为10进制 encryption = int( random_num, 16) ** int(self.public_key, 16) % int(self.modulus, 16) # 将加密后的数据转换为16进制字符串 encryption = format(encryption, 'x') # 返回加密后的字符串 return encryption # 生成params # 根据key和iv对msg进行AES加密,需调用两次 # key: # 第一次: key # 第二次: random_num # iv: 偏移量iv def AES_encrypt(self, msg, key, iv): # 先将msg按需补全至16的倍数 # 需补全的位数 pad = (16 - len(msg) % 16) # 补全 msg = msg + pad * chr(pad) # 将key,iv和msg均以utf-8编码 key = key.encode('utf-8') iv = iv.encode('utf-8') msg = msg.encode('utf-8') # 根据key和iv生成密钥,模式为CBC模式 encryptor = AES.new(key, AES.MODE_CBC, iv) # 加密 encrypt_aes = encryptor.encrypt(msg) # 先将加密后的值进行base64编码 encrypt_text = base64.encodebytes(encrypt_aes) # 将其转换为utf-8字符串 encrypt_text = str(encrypt_text, 'utf-8') # 返回加密后的字符串 return encrypt_text # 根据歌曲song_id,生成需要传输的data # 其中包括params和encSecKey def construct_data(self, song_id): # 生成16位随机数字符串 random_num = self.set_random_num() # 生成encSecKey encSecKey = self.RSA_encrypt( random_num=random_num) # 调用两次AES加密生成params # 初始化歌曲song_info song_info = '{"ids":"[%s]","level":"exhigh","encodeType":"mp3","csrf_token":"477c1bd99fddedb3adc074f47fee2d35"}' % song_id # 第一次加密,传入encText, key和iv first_encryption = self.AES_encrypt( msg=song_info, key=self.key, iv=self.iv) # 第二次加密, 传入first_encryption, random_num和iv encText = self.AES_encrypt( msg=first_encryption, key=random_num, iv=self.iv) # 生成data data = { 'params': encText, 'encSecKey': encSecKey } # 返回data return data # 发送请求,获取下载链接 def get_real_url(self): # 输入歌曲song_id self.song_id = songid # 获取data data = self.construct_data( song_id=self.song_id) # 发送请求 request = requests.post( url=self.url, headers=self.headers, data=data, proxies=proxies, verify=False) # 初始化real_url real_url = '' # 处理返回信息 try: js_text = json.loads(request.text) data = js_text['data'] if len(data) != 0: code = data[0]['code'] # 获取成功 if code == 200: # 歌曲真实地址 real_url = data[0]['url'] else: raise RetryError except: print('生成的params和encSecKey有误!重试中!') raise RetryError # 返回real_url return real_url def download(self): # 获取下载链接 real_url = self.get_real_url() if real_url == '': print('链接获取失败!') raise RetryError else: file = name # 开始下载 try: content = requests.get( url=real_url, headers=self.headers).content with open(file, 'wb') as fp: fp.write(content) except: print('服务器连接出错') raise RetryError for __ in range(6): # 最多尝试6次 if proxynum > (len(proxy) - 1): # 代理自动切换至下一个 proxynum = 0 proxies = proxy[proxynum] proxynum += 1 try: WangyiyunDownload().download() ccimported = True break except: ccimported = False if not exists(name): ccimported = False if ccimported is False: # 下载(普通音质) music = requests.request( "GET", "http://music.163.com/api/song/enhance/download/url?&br=" + str(info['br']) + "&id=" + str(info['id']), headers=headers, proxies=proxies, verify=False) if music.status_code == 200: music = json.loads(music.content) if not music['data']['url']: music = requests.request( "GET", "https://music.163.com/song/media/outer/url?id=" + str(info['id']) + ".mp3", headers=headers, verify=False) if music.status_code != 200: continue else: music = requests.request( "GET", music['data']['url'], headers=headers) else: continue performers = info['artist'].replace(';', ',') cap = performers + " - " + "**" + info['title'] + "**" if ccimported is False: with open(name, 'wb') as f: f.write(music.content) if (path.getsize(name) / 1024) < 100: remove(name) try: if reply.sender.is_self: await reply.delete() except: pass await context.delete() res = '或者你可以点击<a href="https://music.163.com/#/song?id=' + \ str(info['id']) + '">' + \ ' <strong>这里</strong> ' + '</a>' + '前往网页版收听' await bot.send_message(context.chat_id, f"<strong>【{info['title']}】</strong>\n" + "歌曲获取失败,资源获取可能受限,你可以再次尝试。\n" + res, parse_mode='html', link_preview=True) return duration = 0 imagedata = requests.get( info['albumpic'], headers=headers).content if imported is True: await context.edit(f"{title}信息导入中 . . .") tag = eyed3.load(name) duration = int(tag.info.time_secs) tag.initTag() tag = tag.tag tag.artist = info['artist'] tag.title = info['title'] tag.album = info['album'] tag.images.remove('') tag.images.set(6, imagedata, "image/jpeg", u"Media") tag.save(version=eyed3.id3.ID3_DEFAULT_VERSION, encoding='utf-8') br = "" if imported is True: br = "#" + \ str(eyed3.mp3.Mp3AudioFile( name).info.bit_rate[1]) + "kbps " alias = "" if info['alias']: alias = "\n\n__" + info['alias'][0] + "__" cap += "\n#NeteaseMusic " + br + alias await context.edit(f"{title}上传中 . . .") if not exists("plugins/NeteaseMusicExtra/FastTelethon.py"): if not exists("plugins/NeteaseMusicExtra"): mkdir("plugins/NeteaseMusicExtra") for ____ in range(6): # 最多尝试6次 faster = requests.request( "GET", "https://gist.githubusercontent.com/TNTcraftHIM/ca2e6066ed5892f67947eb2289dd6439/raw/86244b02c7824a3ca32ce01b2649f5d9badd2e49/FastTelethon.py") if faster.status_code == 200: with open("plugins/NeteaseMusicExtra/FastTelethon.py", "wb") as f: f.write(faster.content) break else: if exists("plugins/NeteaseMusicExtra/NoFastTelethon.txt"): break try: from NeteaseMusicExtra.FastTelethon import upload_file file = await upload_file(context.client, open(name, 'rb'), name) except: file = name if not exists("plugins/NeteaseMusicExtra/NoFastTelethon.txt"): with open("plugins/NeteaseMusicExtra/NoFastTelethon.txt", "w") as f: f.write("此文件出现表示FastTelethon支持文件在首次运行NeteaseMusic插件时导入失败\n这可能是因为Github服务器暂时性的访问出错导致的\nFastTelethon可以提升低网络性能机型在上传文件时的效率,但是正常情况提升并不明显\n如想要手动导入,可以手动下载:\nhttps://gist.githubusercontent.com/TNTcraftHIM/ca2e6066ed5892f67947eb2289dd6439/raw/86244b02c7824a3ca32ce01b2649f5d9badd2e49/FastTelethon.py\n并放入当前文件夹") await bot.send_message(context.chat_id, '`FastTelethon`支持文件导入失败,上传速度可能受到影响\n此提示仅出现**一次**,手动导入可参考:\n`' + getcwd() + '/plugins/NeteaseMusicExtra/NoFastTelethon.txt`') await context.client.send_file( context.chat_id, file, caption=cap, link_preview=False, force_document=False, thumb=imagedata, attributes=(DocumentAttributeAudio( duration, False, info['title'], performers),) ) try: if reply.sender.is_self: await reply.delete() except: pass try: remove(name) except: pass await context.delete() status = True break else: await context.edit("**未搜索到结果**") sleep(3) await context.delete() status = True break else: continue if status is False: await context.edit(apifailtext) sleep(3) await context.delete() else: # 错误输入 await context.edit(helptext) return
import eyed3 import glob import os from shutil import copyfile path = "./" cp_path = "/media/media/Spotify/" file_type = "mp3" total_path = path + "*" + "." + file_type mp3musics = glob.glob(total_path) for file in mp3musics: mp3 = eyed3.load(file) artist = mp3.tag.artist album = mp3.tag.album directory = cp_path + artist subdirectory = directory + "/" + album filedirectory = subdirectory + "/" + file if not os.path.exists(directory): os.makedirs(directory) if not os.path.exists(subdirectory): os.makedirs(subdirectory) if not os.path.exists(filedirectory): copyfile(file, filedirectory)
def isMono(filename): audiofile = eyed3.load(filename) return audiofile.info.mode == 'Mono'
import os import eyed3 for folder in range(1, 9): path = "./" + str(folder) + '/' if not os.path.isdir(path): os.mkdir(path) files = os.listdir(path) for file in files: filename = path + file if file.endswith(".mp3") or file.endswith(".MP3"): print(file) audiofile = eyed3.load(filename) newfile = path + f'{audiofile.tag.track_num[0]:03d}' + '.mp3' os.rename(filename, newfile) else: os.remove(filename)
song_genre = "Country" elif song_genre not in preserved_genres: song_genre = genre_lookup[parent_lookup[id_lookup[song_genre]]] return song_genre print("Starting to re-label and move songs...") # re-label and move FMA samples for i in range(len(fma_paths)): os.chmod(fma_paths[i], 0o777) if i == len(fma_paths) // 2: print("Halfway done!") filename = fma_paths[i][-10:-4] song_genre = genre_lookup[track_genre_lookup[int(filename)]] if filename not in fma_skips and song_genre not in fma_skips: audiofile = eyed3.load(fma_paths[i]) song_genre = genre_fix(song_genre, filename) audiofile.tag.genre = song_genre audiofile.tag.save() ########## TODO: finish screening song samples for Rock, Electric, and Punk ########## then remove this portion of the script skip_song = False if song_genre == 'Electronic' and int(filename) > 58343: skip_song = True elif song_genre == 'Rock' and filename not in safe_rock: skip_song = True elif song_genre == 'Punk' and int(filename) >= 93983: skip_song = True if not skip_song:
def main() -> int: '''Run the program.''' args = parse_args(sys.argv[1:]) if args.version: print(id3cleaner.__version__) return 2 _setuplogger(loglevel=args.loglevel) filenames = [pathlib.Path(fn) for fn in args.filenames] files_not_found = [fn for fn in filenames if not fn.exists()] if files_not_found: LOG.fatal('The following files were not found: %s', repr(files_not_found)) return 2 # force load of everything up front to make sure it works, then load # lazily later to save cycles LOG.info("Pre-loading all target files...") for filename in filenames: LOG.debug('\tPre-loading %s...', filename) _ = eyed3.load(filename) LOG.info("Pre-load succeeded.") audio_files = (eyed3.load(filename) for filename in filenames) profile = changes.ChangeProfile() for optfield in ('title', 'artist', 'album', 'album_artist', 'track_num', 'genre'): arg = getattr(args, optfield) if arg is not None: formatter = functools.partial(id3_fmt.id3_fmt, arg) change = changes.ComplexID3Change(optfield, formatter) profile.add_change(change) if args.rename: change = changes.SimpleRenameChange(args.rename, args.force_rename) profile.add_change(change) profiles.default_cleaner_profile(profile) if args.rename: change = changes.SimpleRenameChange(args.rename, args.force_rename) profile.add_change(change) if args.picture_file: def get_picture(audio_file): resolved_picture_f = id3_fmt.id3_fmt(args.picture_file, audio_file) picture_file = pathlib.Path(resolved_picture_f) LOG.info('Loading picture file %s...', picture_file) with open(picture_file, 'rb') as picture_fd: picture_file_bytes = picture_fd.read() human_bytes = humanize.naturalsize(len(picture_file_bytes)) LOG.info('Picture file %s loaded (%s).', picture_file, human_bytes) return picture_file_bytes picture_change = changes.ImageID3Change('images', get_picture) profile.add_change(picture_change) nosave_profile = changes.ChangeProfile() if args.rename: change = changes.SimpleRenameChange(args.rename, args.force_rename) nosave_profile.add_change(change) try: for audio_file in audio_files: _handle_audio_file(audio_file, profile, nosave_profile=nosave_profile, dry_run=args.dry_run) except ID3CleanerError as err: LOG.fatal(err) return 2 return 0
def set_id3_tag(path: str, audio_info: Dict): audio = eyed3.load(path) audio.initTag(version=ID3_V1) audio.tag.title = unidecode(audio_info['title']).strip() audio.tag.artist = unidecode(audio_info['artist']).strip() audio.tag.save(version=ID3_V1)
def process_audio_files(currentFile): eyed3.log.setLevel("ERROR") curPath, file = os.path.split(currentFile) if currentFile.lower().endswith((".mp3",)) and not currentFile.startswith(".") \ and os.path.isfile(currentFile): try: mp3File = eyed3.load(currentFile) except: mp3File = "Could not load MP3" try: bitRate = mp3File.info.bit_rate except: bitRate = "" try: sampleRate = mp3File.info.sample_freq except: sampleRate = "Samplerate Unsupported" try: channels = str(mp3File.info.mode) except: channels = "" try: durationSecs = mp3File.info.time_secs duration = str(datetime.timedelta(seconds=durationSecs)) except: duration = "***" try: bits = (audiotools.open(currentFile).bits_per_sample()) except Exception as e: bits = " " # convert mp3 to wav for voice recognition home = str(Path.home()) src = currentFile dst = os.path.join(home, "tempWav.wav") sound = AudioSegment.from_mp3(src) # [10000:] sound.export(os.path.join(home, "tempWav.wav"), format="wav") # Do watermark detection with voice recognition only on testWav.wav srVoiceTestWav = sr.AudioFile(dst) try: with srVoiceTestWav as source: audio = r.record(source, duration=10) recognisedSpeech = str((r.recognize_google(audio))) if "audio" or "jungle" or "audiojungle" in recognisedSpeech: ch = red("WM") if "jungle" in recognisedSpeech: ch = red("WM") if "audi" in recognisedSpeech: ch = red("WM") else: ch = " " except Exception as e: ch = " " wm = "nowm" recognisedSpeech = '' if channels.lower() == "joint stereo" or "stereo": channels = 2 try: rate = int(bitRate[1]) except: rate = "err" vbrTrueFalse = " " if sampleRate == 44100 and channels == 2 and 325 > rate > 315: # and wm != "wmd": errorMp3 = green(" [ok]") else: errorMp3 = red("[ERR]") ###################################################################################### # PRINT MP3 DATA # ###################################################################################### print(errorMp3, sampleRate, bits, channels, ch, vbrTrueFalse, rate, duration[3:-7], file, red(recognisedSpeech)) # Look for wav files and evaluate if currentFile.lower().endswith((".wav",)) and not currentFile.startswith(".") \ and os.path.isfile(currentFile): try: sampleRate = (audiotools.open(currentFile).sample_rate()) ch = "ch" gap = " " except: sampleRate = "BitDepth Unsupported" gap = "" ch = "" try: bits = (audiotools.open(currentFile).bits_per_sample()) except: bits = "" try: channels = int(audiotools.open(currentFile).channels()) except: channels = "" try: durationSecsWav = int( audiotools.open(currentFile).seconds_length()) duration = str(datetime.timedelta(seconds=durationSecsWav)) except: duration = "****" srVoiceTestWav = sr.AudioFile(currentFile) try: with srVoiceTestWav as source: audio = r.record(source, duration=10) # Alternative speech recognition # # recognisedSpeech = str((r.recognize_wit(audio, # key='RGAIIA26NIKLTR5PFPTMZM5MEHUC4MI3', show_all=False))) recognisedSpeech = str((r.recognize_google(audio, ))) if "audio" in recognisedSpeech: ch = red("WM") if "jungle" in recognisedSpeech: ch = red("WM") if "audi" in recognisedSpeech: ch = red("WM") else: ch = " " except Exception as e: ch = " " wm = "nowm" recognisedSpeech = '' if sampleRate == 44100 and bits == 16 and channels == 2: errorWav = green(" [ok]") else: errorWav = red("[ERR]") LACout = "" ###################################################################################### # PRINT WAV DATA # ###################################################################################### print(errorWav, sampleRate, bits, channels, ch, gap, duration[3:], file, red(recognisedSpeech)) # If any other audio file types are present mark as [ERR] if file.lower().endswith((".aac", ".aiff", ".aif", ".flac", ".m4a", ".m4p")) \ and os.path.isfile(currentFile): try: sampleRate = (audiotools.open(currentFile).sample_rate()) except: sampleRate = "Bitdepth Unsupported" try: bits = (audiotools.open(currentFile).bits_per_sample()) except: bits = " " try: channels = int(audiotools.open(currentFile).channels()) except: channels = " " errorWav = red("[ERR]") ch = "" print(errorWav, sampleRate, bits, channels, ch, " ", file)
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: return meta.tag.title 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] except (id3.ID3NoHeaderError, KeyError): try: # file with MP4 tags title = easymp4.EasyMP4(filename)["title"] if title: return 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] 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
if not block: break handle.write(block) return audioURL = sys.argv[1] data = sys.argv[2:6] fileName = validateFileName(data[0].strip()) # this is the name given by user download(audioURL, fileName, ".m4a") # downlaod audio cmd = "ffmpeg -i 'download/" + fileName + ".m4a' -ab 256k 'download/" + fileName + ".mp3'" subprocess.call(cmd, shell=True) # convert m4a to mp3 audiofile = eyed3.load("download/" + fileName + ".mp3") # tagging starts audiofile.initTag(eyed3.id3.ID3_V2_3) audiofile.tag.artist = unicode(data[1].strip()) # artist audiofile.tag.title = unicode(data[0].strip()) # title audiofile.tag.album = unicode(data[2].strip()) # album try: imagedata = requests.get(data[3]).content imgformat = data[3].split(".")[-1].lower() if imgformat == "png": audiofile.tag.images.set(3, imagedata, "image / png") else: audiofile.tag.images.set(3, imagedata, "image / jpeg") except: pass
def mp3data(self, directory, filename): data = {} eyed3.log.setLevel('CRITICAL') audiofile = eyed3.load(filename) tag = audiofile.tag data = {} if isinstance(tag, id3.Tag): artist = tag.artist if tag.artist else None data['artist'] = artist title = tag.title if tag.title else None data['title'] = title album = tag.album if tag.album else None data['album'] = album mod_timestamp = datetime.fromtimestamp(path.getmtime(filename)) pubdate = mod_timestamp.replace(tzinfo=pytz.utc) data['pubdate'] = pubdate if data['album'] and data['title']: data['combined'] = data['title'] + " (" + data['album'] + ")" for date, date_label in [ (tag.release_date, "release date"), (tag.original_release_date, "original release date"), (tag.recording_date, "recording date"), (tag.encoding_date, "encoding date"), (tag.tagging_date, "tagging date"), ]: if date: data['dateid3'] = str(date) track_str = "" (track_num, track_total) = tag.track_num if track_num is not None: track_str = str(track_num) if track_total: track_str += "/%d" % track_total data['track'] = track_str genre = tag.genre # COMM comlist = [] data['desc'] = None for c in tag.comments: if c.text: comlist.append(c.text) # USLT for l in tag.lyrics: if l.text: comlist.append(l.text) if len(comlist) > 0: data['desc'] = max(comlist, key=len) if data['desc'] == None: data['desc'] = 'Unknown' fn = filename.split('/')[-1] dn = filename.split('/')[-2] fileURL = ROOT_URL + urllib.quote(dn + '/' + fn) data['fileURL'] = fileURL data['filesize'] = str(path.getsize(filename)) data['filetype'] = 'application/octet-stream' return data else: raise TypeError("Unknown tag type: " + str(type(tag)))
#!/usr/bin/env python # -*- encoding: utf-8 import os import eyed3 for f in list(os.listdir(".")): if not f.endswith(".mp3"): continue disc, track_num, *_ = f.split("-") disc = int(disc) track_num = int(track_num) if disc == 2: track_num += 21 af = eyed3.load(f) af.tag.track_num = track_num af.tag.save() os.rename(f, f[9:])
music_names.append([]) music_names[i].append(os.path.split(asps[i])[-1]) music_names[i].append(asps[i]) # Strip track no and numbers from the song names using lstrip for i in range(len(music_names)): music_names[i][0]=music_names[i][0].lstrip("0123456789.- ") # Remove extension from song names for i in range(len(music_names)): music_names[i][0] = "".join(music_names[i][0].split('.')[:-1]) # replace '-','_','320','Kbps','kbps' sign with ' ' for i in range(len(music_names)): music_names[i][0] = music_names[i][0].replace("-", " ") music_names[i][0] = music_names[i][0].replace("_", " ") music_names[i][0] = re.sub("\d\d\d\s*kbps"," ", music_names[i][0], flags=re.I) # remove anything in between (),[],{} and replace multiple spaces for i in range(len(music_names)): music_names[i][0] = re.sub(r"[\(\[].*?[\)\]]", "", music_names[i][0]) music_names[i][0] = re.sub(" +"," ", music_names[i][0]) for i in range(len(music_names)): audiofile = eyed3.load(music_names[i][1]) song_directory = scrape_google_image(music_names[i][0] + " song cover art", name=music_names[i][0], max_num=1) song_filename = os.path.join(song_directory, os.listdir(song_directory)[0]) Image.open(song_filename) tkinter_window(song_filename, audiofile)
def create_album_directory(): if not os.path.isdir(os.path.join(root, new_mp3_track.artist, new_mp3_track.album).replace("\\", "/")): os.makedirs(os.path.join(root, new_mp3_track.artist, new_mp3_track.album).replace("\\", "/")) return f"Directory '{new_mp3_track.artist} / {new_mp3_track.album}' didn't exist, making it now." # OS Walk through path for root, directories, files in os.walk(path, topdown=False): # Loop through files for name in files: if name.endswith('mp3'): # Load MP3 file audio_file = eyed3.load(os.path.join(root, name)) # Increment counter counter += 1 # Set Variables new_mp3_track = MP3Track(audio_file.tag.artist, audio_file.tag.album, audio_file.tag.title) print(f"Loaded {new_mp3_track}") # Set files and directories original_path = os.path.join(root, name) destination_path = os.path.join(root, new_mp3_track.artist, new_mp3_track.album, new_mp3_track.title) + ".mp3" # Get Size size = str(os.path.getsize(original_path))
print('Done. %d tracks detected.' % len(library)) gmusic_albums = set() for track in library: artist = track['albumArtist'].lower() album = track['album'].lower() gmusic_albums.add('%s - %s' % (artist, album)) print('Loaded info for all tracks.') print() print('Loading file library...') mp3s = glob.glob('%s/**/*.mp3' % MUSIC_LIBRARY_PATH, recursive=True) print('%d mp3s found.' % len(mp3s)) mp3_tags = [] for file in mp3s: mp3_tags.append(eyed3.load(file).tag) offline_albums = set() for track in mp3_tags: artist = track.album_artist.lower() if track.album_artist else '' album = track.album.lower() if track.album else '' offline_albums.add('%s - %s' % (artist, album)) print('Loaded info for all tracks.') print() for gmusic_album in gmusic_albums.copy(): for offline_album in offline_albums: if fuzz.ratio(gmusic_album, offline_album) > MINIMUM_FUZZ_RATIO: gmusic_albums.remove(gmusic_album) offline_albums.remove(offline_album)