def info(filename): try: audio = mutagen.File(filename, options=ogg_formats) except AttributeError: audio = OggVorbis(filename) if audio is None and FLAC is not None: # FLAC with ID3 try: audio = FLAC(filename) except FLACNoHeaderError: pass if audio is None: raise IOError("file type could not be determined") Kind = type(audio) for klass in globals().values(): if Kind is getattr(klass, 'MutagenType', None): return klass(filename, audio) raise IOError("file type could not be determined")
def get_primary_image(self): """Returns the primary embedded image""" try: tag = FLAC(self["~filename"]) except Exception: return None covers = tag.pictures if not covers: return super(FLACFile, self).get_primary_image() covers.sort(key=lambda c: APICType.sort_key(c.type)) cover = covers[0] fileobj = get_temp_cover_file(cover.data) return EmbeddedImage(fileobj, cover.mime, cover.width, cover.height, cover.depth, cover.type)
def test_flac_fileTagsUpdate(self): f = Path(filedir() / 'data/9348620_take_care.flac') db = core.Database() core.addTrackToDB(f, db) tr = db.db[9348620] tr.fileTagsUpdate(force=True) audiof = FLAC(tr.file_path) self.assertEqual(audiof['ARTIST'], ['Ronny Vergara']) self.assertEqual(audiof['DATE'], ['2017']) # we save only year into the file self.assertEqual(audiof['GENRE'], ['Techno (Peak Time / Driving / Hard)']) self.assertEqual(audiof['ORGANIZATION'], ['Dolma Records']) self.assertEqual(audiof['TITLE'], ['Take Care (Hackler & Kuch Remix)']) self.assertEqual(audiof['ALBUM'], ['Remixes Compilation VOL02']) self.assertEqual(audiof['BPM'], ['126'])
def saveArtwork(self): if Path(self.file_name).suffix == ".flac": audiof = FLAC(self.file_path) if len(audiof.pictures) != 0: return dl_img = urllib3.PoolManager(cert_reqs='CERT_NONE', assert_hostname=False).request('GET', self.artwork_url).data img = Picture() img.type = 3 img.desc = 'artwork' img.data = dl_img audiof.add_picture(img) elif Path(self.file_name).suffix == ".mp3": audiof = ID3(self.file_path) if hasattr(audiof, "pictures") and len(audiof.pictures) != 0: return dl_img = urllib3.PoolManager(cert_reqs='CERT_NONE', assert_hostname=False).request('GET', self.artwork_url).data audiof.add(mutagen.id3.APIC(3, 'image/jpeg', 3, 'Front cover', dl_img)) audiof.save()
def _generate_image_from_flac(self, flacPath): # if we don't have the python module to # extract image from flac, we just return # default file's icon try: from mutagen.flac import FLAC except ImportError: return FILE_ICON try: audio = FLAC(flacPath) art = audio.pictures return self._generate_image_from_art(art, flacPath) except IndexError: return FILE_ICON except TypeError: return FILE_ICON
def setImage(self, song): audio = FLAC(song.get("~filename", "")) ## if file has no images -> leave if (audio.pictures is None) or (len(audio.pictures) <= 0): return ## if first image is frontcover -> leave img = audio.pictures[0] if img.type == 3: return ## ok, we have to lookup the data... images = list() frontcover = None for img in audio.pictures: if img.type == 3: frontcover = img else: images.append(img) ## if file has no frontcover -> leave if (frontcover is None): print( _("No frontcover found in {!s}.").format( song.get("~filename", ""))) return ## first,clear all pictures, then add the frontcover try: audio.clear_pictures() audio.add_picture(frontcover) except: self.printError() return False ## now add all other images for img in images: try: audio.add_picture(img) except: self.printError() return False audio.save() app.window.emit("artwork-changed", [song]) return
def library_cleaner(library_path): # the below regex is used to filter out characters that Windows doesn't like in directory names folder_regex = re.compile(r'\*|\\|\||<|>|/|\?|:|"') # program starts by cycling through all of the artist subfolders in the main music folder for artist_name in os.listdir(library_path): # the artist folder path is obtained by combining the main music folder path with the artist name artist_folder = library_path + '/' + artist_name # the program then iterates through all of the albums in the artist's folder for album_name in os.listdir(artist_folder): album_folder = artist_folder + '/' + album_name # this determines if the first file in the folder is an audio file or not. TODO - could be cleaned up to actually iterate through items in folder if os.listdir(album_folder): if Path(album_folder + '/' + os.listdir(album_folder)[0] ).suffix != '.flac' or '.mp3' or '.m4a': first_track_filename = os.listdir(album_folder)[-1] else: first_track_filename = os.listdir(album_folder)[0] # if the file is an mp3 if Path(first_track_filename).suffix == '.mp3': first_track = ID3(album_folder + '/' + first_track_filename) real_album_name = re.sub(folder_regex, '', first_track['TALB'].text[0]) print(f'Renamed {album_name} to {real_album_name}.') os.rename(album_folder, os.path.join(artist_folder, real_album_name)) # if the file is a flac if Path(first_track_filename).suffix == '.flac': first_track = FLAC(album_folder + '/' + first_track_filename) real_album_name = re.sub(folder_regex, '', first_track['album'][0]) print(f'Renamed {album_name} to {real_album_name}.') os.rename(album_folder, os.path.join(artist_folder, real_album_name)) # if the file is an m4a if Path(first_track_filename).suffix == '.m4a': first_track = MP4(album_folder + '/' + first_track_filename) real_album_name = re.sub(folder_regex, '', str(first_track['\xa9alb'][0])) print(f'Renamed {album_name} to {real_album_name}.') os.rename(album_folder, os.path.join(artist_folder, real_album_name))
def get_audio_metadata(filename): '''take a path to a music file, grab the metadata with mutagen return a standardized dict, or None if it's not an audio file or there's no MusicBrainz data output fields defined at <http://wiki.musicbrainz.org/PicardTagMapping> ''' dict = None # doing this based on extension is wrong # ~* filetype is metadata, no gods no masters *~ ext = os.path.splitext(filename)[1].lower() if ext == '.mp3': file = ID3(filename) dict = {} dict['musicbrainz_trackid'] = [ file['UFID:http://musicbrainz.org'].data ] dict['tracknumber'] = [file['TRCK'].text[0].split('/')[0]] dict['title'] = file['TIT2'].text dict['musicbrainz_artistid'] = file['TXXX:MusicBrainz Artist Id'].text dict['artist'] = file['TPE1'].text if 'TXXX:MusicBrainz Album Artist Id' in file: dict['musicbrainz_albumartistid'] = file[ 'TXXX:MusicBrainz Album Artist Id'].text # ignore TPE2 (which MB uses for album artist name), it's rarely there # and it's being misused anyhow dict['musicbrainz_albumid'] = file['TXXX:MusicBrainz Album Id'].text dict['album'] = file['TALB'].text # sane formats already have standardized field names elif ext == '.ogg': dict = OggVorbis(filename) elif ext == '.flac': dict = FLAC(filename) return dict
def make_m3u(self, pl_directory): if self.no_m3u_for_playlists: return track_list = ["#EXTM3U"] rel_folder = os.path.basename(os.path.normpath(pl_directory)) pl_name = rel_folder + ".m3u" for local, dirs, files in os.walk(pl_directory): dirs.sort() audio_rel_files = [ # os.path.abspath(os.path.join(local, file_)) # os.path.join(rel_folder, os.path.basename(os.path.normpath(local)), file_) os.path.join(os.path.basename(os.path.normpath(local)), file_) for file_ in files if os.path.splitext(file_)[-1] in EXTENSIONS ] audio_files = [ os.path.abspath(os.path.join(local, file_)) for file_ in files if os.path.splitext(file_)[-1] in EXTENSIONS ] if not audio_files or len(audio_files) != len(audio_rel_files): continue for audio_rel_file, audio_file in zip(audio_rel_files, audio_files): try: pl_item = ( EasyMP3(audio_file) if ".mp3" in audio_file else FLAC(audio_file) ) title = pl_item["TITLE"][0] artist = pl_item["ARTIST"][0] length = int(pl_item.info.length) index = "#EXTINF:{}, {} - {}\n{}".format( length, artist, title, audio_rel_file ) except: # noqa continue track_list.append(index) if len(track_list) > 1: with open(os.path.join(pl_directory, pl_name), "w") as pl: pl.write("\n\n".join(track_list))
def convert_file(self, full_path): try: out_path = self.get_out_path(full_path) lame_options = self.lame_options or ['--preset', 'standard', '-h'] metadata = FLAC(full_path) try: os.makedirs(os.path.dirname(out_path)) except OSError as e: if e.errno != 17: raise # only raise if not "file exists" error flac_p = subprocess.Popen( [self.flac, '-s', '-d', '--stdout', full_path], stdout=subprocess.PIPE, preexec_fn=ignore_sigint) lame_cmd = [self.lame] + lame_options + ['--quiet', '-', out_path] lame_p = subprocess.Popen(lame_cmd, stdin=flac_p.stdout, preexec_fn=ignore_sigint) flac_p.wait() lame_p.wait() # now apply gain if self.apply_mp3gain: mp3gain_cmd = [self.mp3gain, '-q', '-T', '-r', '-k', out_path] subprocess.check_call(mp3gain_cmd, stdout=open('/dev/null', 'wb')) # finally, correct the tags id3data = File(out_path, easy=True) for attr in ('title', 'artist', 'album', 'date', 'genre', 'tracknumber'): id3data[attr] = metadata.get(attr) id3data.save() except Exception as e: status_queue.put(('ERROR', full_path, str(e))) if os.path.exists(out_path): os.unlink(out_path) else: status_queue.put(('OK', full_path, out_path))
def removeImage(self, song): audio = FLAC(song.get("~filename", "")) store = False ## if file has no images -> leave if (audio.pictures is None) or (len(audio.pictures) <= 0): return images = list() for img in audio.pictures: if img.type == self.type \ and img.desc == self.desc: store = True else: images.append(img) if store: ## first,clear all pictures, then add the frontcover try: audio.clear_pictures() except: self.printError() return False ## now add all other images for img in images: try: audio.add_picture(img) except: self.printError() return False audio.save() ## and now count the images count = "0" ## if file has no images -> set to 0 if (audio.pictures is None) or (len(audio.pictures) <= 0): pass else: count = str(len(audio.pictures)) if not "pictures" in song: song["pictures"] = count if song["pictures"] <> count: song["pictures"] = count app.window.emit("artwork-changed", [song]) return
def UpdateTag(self, filts=None): if self.filePath != '': tags = None if os.path.splitext(self.filePath)[1] == '.mp3': try: tags = EasyID3(self.filePath) except mutagen.id3.ID3NoHeaderError: try: tags = mutagen.File(self.filePath, easy=True) tags.add_tags() except Exception as ex: print(("Error while loading mp3 tags for " + self.filePath + ": " + str(ex))) return False elif os.path.splitext(self.filePath)[1] == '.flac': try: tags = FLAC(self.filePath) except Exception as ex: print(("Error while loading flac tags for " + self.filePath + ": " + str(ex))) return False else: print(("File extension not supported: " + str(self.filePath))) return False try: self.applyFilts(tags, 'albumartist', self.podcast.author, filts) if self.author != '': self.applyFilts(tags, 'artist', self.author, filts) else: self.applyFilts(tags, 'artist', self.podcast.author, filts) self.applyFilts(tags, 'title', self.title, filts) self.applyFilts(tags, 'album', self.podcast.title, filts) self.applyFilts(tags, 'tracknumber', str(self.num), filts) self.applyFilts(tags, 'genre', defaultGenre, filts) self.applyFilts(tags, 'date', str(self.pubDate.year), filts) tags.save() except Exception as ex: print( ("Couldn't add tag to " + self.filePath + ": " + str(ex))) return False return True
def tag(self) -> None: if self.filepath is None: raise AttributeError(f'Filepath of "{self.title}" not set') if self.ext == "flac": audio = FLAC(self.filepath) for k, v in self.__dict__.items(): # TODO: fix composer glitch where it displays as list if ( k.upper() in ["ARTIST", "COMPOSER", "GENRE", "ALBUMARTIST"] and type(v) is list ): audio[k.upper()] = ", ".join(v) elif k not in ["filepath", "cover_url", "pos", "length"]: audio[k] = str(v) audio.save() elif self.ext == "m4a": audio = MP4(self.filepath) for k, v in self.__dict__.items(): if ( k not in [ "filepath", "cover_url", "pos", "length", "date", "label", "url", "tracktotal", "disctotal", "artist", ] and v is not None ): audio[_mp4_keys[k]] = v elif k in ["artist"]: audio[_mp4_keys[k]] = ", ".join(v) audio[_mp4_keys["tracknumber"]] = [(self.tracknumber, self.tracktotal)] audio[_mp4_keys["discnumber"]] = [(self.discnumber, self.disctotal)] audio["covr"] = self.images audio.save()
def audio_lsb_encode(file_name, message): # add a end of transmission character to the end of the message EOT = chr(4) message = message + EOT # Convert the message into a array of bits ba = bitarray.bitarray() ba.frombytes(message.encode(encoding="latin_1", errors="replace")) bit_array = [int(i) for i in ba] new_file_name = "media/lsb_" + file_name.split("/")[-1] i = 0 # open the original audio file with sf.SoundFile(file_name, "r") as audio: audio_data = audio.read(frames=-1, dtype='int16') # iterate over the frames on each channel of sound and change least sig bits for channel in range(0, audio.channels): for frame in range(0, audio.frames): if i < len(bit_array): old_frame = audio_data[frame][channel] # create duplicate frame with no sign old_frame_dup = old_frame if old_frame_dup < 0: old_frame_dup *= -1 audio_data[frame][channel] = get_new_frame( bin(old_frame_dup), bit_array[i], old_frame < 0) i += 1 if i >= len(bit_array): break if i >= len(bit_array): break # write the changed audio data to a new file sf.write(new_file_name, audio_data, audio.samplerate) # write FLAC metadata into new audiofile if audio.format == "FLAC": orig_audio = FLAC(file_name) orig_audio.save(new_file_name) audio.close()
def sendAudio(chat_id, audio, lang, music, image=None, youtube=False): bot.sendChatAction(chat_id, "upload_audio") try: url = "https://api.telegram.org/bot" + token + "/sendAudio" if os.path.isfile(audio): audio = open(audio, "rb") try: tag = EasyID3(audio.name) duration = MP3(audio.name).info.length except mutagen.id3._util.ID3NoHeaderError: tag = FLAC(audio.name) duration = tag.info.length data = { "chat_id": chat_id, "duration": duration, "performer": tag['artist'], "title": tag['title'] } file = {"audio": audio, "thumb": requests.get(image).content} try: request = requests.post(url, params=data, files=file) except: request = requests.post(url, params=data, files=file) if request.status_code == 413: bot.sendMessage( chat_id, translate(lang, "The song is too big to be sent")) else: if youtube == False: audio = request.json()['result']['audio']['file_id'] write_db( "INSERT INTO DWSONGS(id, query, quality) values('%s', '%s', '%s')" % (music, audio, qualit[chat_id])) else: bot.sendAudio(chat_id, audio) except telepot.exception.TelegramError: bot.sendMessage( chat_id, translate(lang, "Sorry the track doesn't seem readable on Deezer :(")) except Exception as a: logging.warning(a) bot.sendMessage( chat_id, translate(lang, "Sorry for some reason I can't send the track"))
def write_metadata(self): if MUTAGEN: if "MP3" in self.__audio_codec: # Prima scrive i tag v1 e v2, poi rimuove i v2 self.write_ID3v2() self.remove_ID3v2() elif "ogg" in self.__gst_type: tags = OggVorbis(self.__filepath) tags["tracknumber"] = unicode(int( self.get_tag("track_number"))) tags["title"] = unicode(self.get_tag("title")) tags["artist"] = unicode(self.get_tag("artist")) tags["album"] = unicode(self.get_tag("album")) tags["date"] = unicode(self.get_tag("year")) tags["genre"] = unicode(self.get_tag("genre")) tags["comment"] = unicode(self.get_tag("comment")) tags["albumartist"] = unicode(self.get_tag("album_artist")) tags["composer"] = unicode(self.get_tag("composer")) tags["discnumber"] = unicode(self.get_tag("disc_number")) # TODO: Come salvare la copertina in un file Vorbis??? # Questo non funziona: #tags["coverart"] = [self.get_tag("cover")] tags.save(self.__filepath) elif "flac" in self.__gst_type: tags = FLAC(self.__filepath) tags["tracknumber"] = unicode(int( self.get_tag("track_number"))) tags["title"] = unicode(self.get_tag("title")) tags["artist"] = unicode(self.get_tag("artist")) tags["album"] = unicode(self.get_tag("album")) tags["date"] = unicode(self.get_tag("year")) tags["genre"] = unicode(self.get_tag("genre")) tags["comment"] = unicode(self.get_tag("comment")) tags["albumartist"] = unicode(self.get_tag("album_artist")) tags["composer"] = unicode(self.get_tag("composer")) tags["discnumber"] = unicode(self.get_tag("disc_number")) # TODO: Come salvare la copertina in un file FLAC??? # Questo non funziona: #tags.add_picture(self.get_tag("cover")) tags.save(self.__filepath)
def getCoverPixmap(currentSong): songPath = Path.home().joinpath('Music').joinpath(currentSong['file']) coverPixmap = QPixmap() artFound = False if songPath.suffix.lower() == '.flac': artMetadata = FLAC(str(songPath)).pictures if artMetadata: embeddedCover = artMetadata[0].data coverPixmap.loadFromData(embeddedCover) artFound = True elif songPath.suffix.lower() == '.mp3': tagData = MP3(str(songPath)).tags if 'APIC:' in tagData: embeddedCover = tagData['APIC:'].data coverPixmap.loadFromData(embeddedCover) artFound = True elif songPath.suffix.lower() == '.m4a': tagData = MP4(str(songPath)).tags if 'covr' in tagData: embeddedCover = tagData['covr'][0] coverPixmap.loadFromData(embeddedCover) artFound = True elif songPath.suffix.lower() == '.ogg': tagData = OggVorbis(str(songPath)).tags #if 'METADATA_BLOCK_PICTURE' in tagData: # embeddedCover = base64.b64decode(tagData['METADATA_BLOCK_PICTURE'][0]) # print(tagData['METADATA_BLOCK_PICTURE'][0]) # coverPixmap.loadFromData(embeddedCover) # artFound = True #elif: if not artFound: albumCoverPath = songPath.parent.joinpath('cover.jpg') if albumCoverPath.exists(): coverPixmap = QPixmap(str(albumCoverPath)) artFound = True if artFound: return coverPixmap.scaled(500, 500, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) else: return None
def main(path): mp3s = get_files_of_type('mp3', path) flacs = get_files_of_type('flac', path) missing_mp3s = [mp3 for mp3 in mp3s if mp3_has_missing_info(load_mp3(mp3))] missing_flacs = [ flac for flac in flacs if flac_has_missing_info(FLAC(flac)) ] print('{} mp3s, {} flacs'.format(len(missing_mp3s), len(missing_flacs))) print('{} mp3s, {} flacs'.format(missing_mp3s, missing_flacs)) for mp3_path in missing_mp3s: update_mp3_id3(mp3_path) for flac_path in missing_flacs: update_flac_id3(flac_path) print('Done!!')
def write_tags(song, data): try: tag = FLAC(song) tag.delete() images = Picture() images.type = 3 images.data = data['image'] tag.clear_pictures() tag.add_picture(images) tag['lyrics'] = data['lyric'] except FLACNoHeaderError: tag = File(song, easy=True) tag['artist'] = data['artist'] tag['title'] = data['music'] tag['date'] = data['year'] tag['album'] = data['album'] tag['tracknumber'] = data['tracknum'] tag['discnumber'] = data['discnum'] tag['genre'] = data['genre'] tag['albumartist'] = data['ar_album'] tag['author'] = data['author'] tag['composer'] = data['composer'] tag['copyright'] = data['copyright'] tag['bpm'] = data['bpm'] tag['length'] = data['duration'] tag['organization'] = data['label'] tag['isrc'] = data['isrc'] tag['replaygain_*_gain'] = data['gain'] tag['lyricist'] = data['lyricist'] tag.save() try: audio = ID3(song) audio.add( APIC(encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=data['image'])) audio.add( USLT(encoding=3, lang=u"eng", desc=u"desc", text=data['lyric'])) audio.save() except _util.ID3NoHeaderError: pass
def write_tags(self, recording): errors = [] for track in recording.tracks: try: audio = FLAC(os.path.join(self.root_path, track.filename)) audio["ALBUM"] = recording.title audio["TITLE"] = track.title audio["ARTIST"] = track.artist audio["COMPOSER"] = track.composer audio["GENRE"] = track.genre audio["TRACKNUMBER"] = str(track.track_num) audio["TRACKTOTAL"] = str(len(recording.tracks)) if recording.recording_date is not None: audio["DATE"] = str(recording.recording_date.year) audio.save() except Exception as exc: errors.append(f"{track.filename} {str(exc)}") return errors
def convertFlacToMpthree(file, format="mp3", bitrate="320k", outFileLocation=""): if not outFileLocation: outPath = os.path.join(os.path.dirname(file) + "/converted") else: outPath = outFileLocation # Create folder is it doesn't already exist. if not os.path.exists(outPath): os.makedirs(outPath) audioName = os.path.splitext(os.path.basename(file))[0] fileName = os.path.join(outPath + f"/{audioName}." + format) # print("-----", fileName) # Convert audio sound = AudioSegment.from_file(file) sound.export(fileName, format=format, bitrate=bitrate, tags=mediainfo(file)["TAG"]) # Add album cover audiofile = eyed3.load(fileName) if (audiofile.tag == None): audiofile.initTag() var = FLAC(file) pics = var.pictures for p in pics: if p.type == 3: # Front cover # print("\nFound front cover") # print(p.data) audiofile.tag.images.set(3, p.data, "image/jpeg") """ You have to set the ID3 version to "V2.3", otherwise the photo won't show up for the file icon. https://stackoverflow.com/questions/38510694/how-to-add-album-art-to-mp3-file-using-python-3#39316853 """ audiofile.tag.save(version=eyed3.id3.ID3_V2_3)
def technical(file): tag = TinyTag.get(file) audio = FLAC(file) # Get minutes and seconds m, s = divmod(int(audio.info.length), 60) h, m = divmod(m, 60) print BOLD + "File:" + END, os.path.basename(file) print BOLD + "Audio offset:" + END, tag.audio_offset print BOLD + "Bitrate:" + END, int(tag.bitrate), "kbps" print BOLD + "Channels:" + END, audio.info.channels print BOLD + "Filesize:" + END, round((float(tag.filesize) / 1024) / 1024, 2), "MiB" # Minutes and seconds if h > 0: print BOLD + "Length:" + END, "%02dh %02dm %02ds" % (h, m, s) else: print BOLD + "Length:" + END, "%02dm %02ds" % (m, s)
def resolve_flac_metadata(song, path, picture, config): try: tagger = FLAC(path) except mutagen.flac.FLACNoHeaderError: raise InvalidFileError() tagger["title"] = song.name tagger["album"] = song.album.name tagger["artist"] = song.get_primary_artist_name(config) tagger["albumartist"] = song.album.get_primary_artist_name(config) tagger["tracknumber"] = str(song.track_number) tagger["discnumber"] = str(song.disc_number) if picture: flac_picture = FLACPicture() flac_picture.type = 3 flac_picture.desc = "Cover" flac_picture.mime = picture["mime"] flac_picture.data = picture["data"] tagger.add_picture(flac_picture) tagger.save()
def regenerateCover(track): if FileType.objects.filter( name="mp3").count() == 1 and FileType.objects.filter( name="flac").count() == 1: mp3Type = FileType.objects.get(name="mp3") flacType = FileType.objects.get(name="flac") coverPath = "/ManaZeak/static/img/covers/" track.coverLocation = "" if track.fileType == mp3Type: try: audioTag = ID3(track.location) except ID3NoHeaderError: audioTag = ID3() if 'APIC:' in audioTag: front = audioTag['APIC:'].data # Creating md5 hash for the cover md5Name = hashlib.md5() md5Name.update(front) # Check if the cover already exists and save it if not os.path.isdir(coverPath): os.mkdir(coverPath) if not os.path.isfile(coverPath + md5Name.hexdigest() + ".jpg"): with open(coverPath + md5Name.hexdigest() + ".jpg", 'wb') as img: img.write(front) track.coverLocation = md5Name.hexdigest() + ".jpg" elif track.fileType == flacType: audioFile = FLAC(track.location) pictures = audioFile.pictures if len(pictures) != 0: # Creating md5 hash for the cover md5Name = hashlib.md5() md5Name.update(pictures[0].data) # Check if the cover already exists and save it if not os.path.isfile(coverPath + md5Name.hexdigest() + ".jpg"): with open(coverPath + md5Name.hexdigest() + ".jpg", 'wb') as img: img.write(pictures[0].data) track.coverLocation = md5Name.hexdigest() + ".jpg" track.save()
def show_details(): # spliting name of the file from extension file_data = os.path.splitext(filename) global bitrate if file_data[1] == ".mp3": audio = MP3(filename) total_length = audio.info.length bitrate = audio.info.bitrate bitrate = round(bitrate / 1000) elif file_data[1] == ".flac": audio = FLAC(filename) total_length = audio.info.length bitrate = audio.info.bitrate bitrate = round(bitrate / 1000) else: # loading the sound and store it into variable a = mixer.Sound(filename) # get the length of stored sound in seconds total_length = a.get_length() bitrate = "-" # take totallength and calculating remainder mins, secs = divmod(total_length, 60) # rounding mins = round(mins) secs = round(secs) global timeformat # showing minutes and seconds in 2 digits format timeformat = "{:02d}:{:02d}".format(mins, secs) #lenghtlabel["text"] = "Total lenght: " + timeformat # THREADING - first argument function, arguments - argument of the function t1 = threading.Thread(target=start_count, args=(total_length, )) # + calling it t1.start()
def resolve_flac_metadata(config: dict, track: Track, path: str, cover: Optional[Cover]) -> None: try: tagger = FLAC(path) except mutagen.flac.FLACNoHeaderError: raise InvalidFileError() tagger["title"] = track.name tagger["album"] = track.album.name tagger["artist"] = [artist.name for artist in track.artists] tagger["albumartist"] = [artist.name for artist in track.album.artists] tagger["tracknumber"] = str(track.track_number) tagger["discnumber"] = str(track.disc_number) if cover: flac_picture = FLACPicture() flac_picture.type = 3 flac_picture.desc = "Cover" flac_picture.mime = cover.mime flac_picture.data = cover.data tagger.add_picture(flac_picture) tagger.save()
def get_image_from_flac(self, filename, return_buffer=False): """ Fetch image from flac file :param filename: file name :param return_buffer: True - return image buffer, False - return Pygame image :return: image or None if not found """ try: pictures = FLAC(filename).pictures if pictures: data = pictures[0].data buffer = BytesIO(data) if return_buffer: return buffer else: return pygame.image.load(buffer).convert_alpha() else: return None except: return None
def tag_flac(self, file_path, track_info, album_info, album_art_path=None): tagger = FLAC(file_path) self._meta_tag(tagger, track_info, album_info, 'flac') if self.fmtopts['embed_album_art'] and album_art_path is not None: pic = Picture() with open(album_art_path, 'rb') as f: pic.data = f.read() pic.type = PictureType.COVER_FRONT pic.mime = u"image/jpeg" try: img = cv2.imread(album_art_path) pic.height, pic.width, channels = img.shape except Exception as e: pic.width = 1280 pic.height = 1280 pic.depth = 24 tagger.add_picture(pic) tagger.save(file_path)
def process_metadata(self, metadata): Log('Reading FLAC tags') try: tags = FLAC(self.filename) except: Log('An error occurred while attempting to parse the FLAC file: ' + self.filename) return # Posters valid_posters = [] for poster in tags.pictures: poster_name = hashlib.md5(poster.data).hexdigest() valid_posters.append(poster_name) if poster_name not in metadata.posters: Log('Adding embedded art from FLAC file: ' + self.filename) metadata.posters[poster_name] = Proxy.Media(poster.data) else: Log('Skipping embedded art since its already added') return valid_posters
def getImageFromTagFLAC(self, pathfile, pathimage=None, nameimage='cover'): """Extract Cover b64 from tag FLAC file media.""" mediafile = FLAC(pathfile) if 'pictures' in dir(mediafile): picture = mediafile.pictures[0] extensions = { "image/jpeg": "jpg", "image/png": "png", "image/gif": "gif" } ext = extensions.get(picture.mime, "jpg") if pathimage is None: imagefinal = path.join(path.dirname(pathfile), 'cover' + '.' + ext) else: imagefinal = path.join(pathimage, nameimage + '.' + ext) with open(imagefinal, "wb") as h: h.write(picture.data) return True return False