How to use the mutagen.File function in mutagen

To help you get started, we’ve selected a few mutagen examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github thebigmunch / gmusicapi-wrapper / gmusicapi_wrapper / gmusicapi_wrapper.py View on Github external
title = song.get('title', "")
				artist = song.get('artist', "")
				album = song.get('album', "")

				logger.debug(
					"Downloading {title} -- {artist} -- {album} ({song_id})".format(
						title=title, artist=artist, album=album, song_id=song_id
					)
				)

				suggested_filename, audio = self.api.download_song(song_id)

				with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp:
					temp.write(audio)

				metadata = mutagen.File(temp.name, easy=True)

				if "%suggested%" in template:
					template = template.replace("%suggested%", suggested_filename.replace('.mp3', ''))

				if os.name == 'nt' and cygpath_re.match(template):
					template = convert_cygwin_path(template)

				if template != os.getcwd():
					filepath = template_to_filepath(template, metadata) + '.mp3'

					dirname, basename = os.path.split(filepath)

					if basename == '.mp3':
						filepath = os.path.join(dirname, suggested_filename)
				else:
					filepath = suggested_filename
github akpw / batch-mp-tools / batchmp / tags / extern / mediafile.py View on Github external
unreadable_exc = (
            mutagen.mp3.error,
            mutagen.id3.error,
            mutagen.flac.error,
            mutagen.monkeysaudio.MonkeysAudioHeaderError,
            mutagen.mp4.error,
            mutagen.oggopus.error,
            mutagen.oggvorbis.error,
            mutagen.ogg.error,
            mutagen.asf.error,
            mutagen.apev2.error,
            mutagen.aiff.error,
        )
        try:
            self.mgfile = mutagen.File(path)
        except unreadable_exc as exc:
            raise UnreadableFileError(path)
        except IOError as exc:
            if type(exc) == IOError:
                # This is a base IOError, not a subclass from Mutagen or
                # anywhere else.
                raise
            else:
                raise MutagenError(path, exc)
        except Exception as exc:
            # Isolate bugs in Mutagen.
            raise MutagenError(path, exc)

        if self.mgfile is None:
            # Mutagen couldn't guess the type
            raise FileTypeError(path)
github MeanEYE / Sunflower / sunflower / plugins / rename_extensions / audio_metadata.py View on Github external
def get_new_name(self, old_name, new_name):
		"""Get modified name"""
		basename, extension = os.path.splitext(new_name)
		path = os.path.join(self._parent._parent._parent.get_active_object().path, old_name)
		template = self._entry_template.get_text()
		tags = mutagen.File(path, easy=True)

		# check if filetype is supported by mutagen
		if tags is None:
			return new_name

		# fill template
		for k, v in self._templates.items():
			try:
				template = string.replace(template, k, tags[v[0]][0])
			except KeyError:
				template = string.replace(template, k, '')

		# replace unwanted characters
		str_rep = self._combobox_replace.get_active_text()
		for c in self._entry_replace.get_text():
			template = string.replace(template, c, str_rep)
github cgoldberg / audiotools / tagging / old_audio_meta_tag.py View on Github external
def retag(filepath):
    logger.debug('Loading File: %r' % filepath)
    audio = File(filepath, easy=True)
    if audio is None:
        logger.debug('Invalid Audio File: %r' % filepath)
    else:
        try:
            artist, title = get_artist_title_from_filename(filepath)
        except ValueError:
            return
        try:
            clear_and_set_tags(audio, artist, title)
        except Exception:
            logger.debug('Invalid Audio File: %r' % filepath)
        logger.info('%s - %s' % (artist, title))
github YetAnotherNerd / whatlastgenre / wlg / mediafile.py View on Github external
def __init__(self, path, filename, v23sep=None):
        self.fullpath = os.path.join(path, filename)
        self.filename = filename
        self.v23sep = v23sep
        self.ext = os.path.splitext(filename)[1].lower()[1:]
        self.dirty = False
        try:
            self.stat = os.stat(self.fullpath)
            self.muta = mutagen.File(self.fullpath, easy=True)
        except (IOError, OSError) as err:
            raise TrackError(err)
        if not self.muta:
            raise TrackError('unknown mutagen error')
github hbashton / spotify-ripper / spotify_ripper / utils.py View on Github external
def audio_file_duration(audio_file):
        if (path_exists(audio_file)):
            _file = mutagen.File(audio_file)
            if _file is not None and _file.info is not None:
                return _file.info.length
        return None
github henkelis / sonospy / sonospy / gettags.py View on Github external
try:
                    c.execute("""select created, lastmodified, folderart from tags where path=? and filename=?""",
                                (filepath, fn))
                    row = c.fetchone()
                    if row:
                        create, lastmod, art = row
                        if create == created and lastmod == lastmodified and art == folderart:
                            get_tags = False
                except sqlite3.Error, e:
                    errorstring = "Error checking file created: %s" % e.args[0]
                    filelog.write_error(errorstring)

                if get_tags:                    
                
                    try:
                        kind = File(ffn, easy=True)
                    except Exception:
                        # note - Mutagen raises exceptions as various types, including Exception
                        #        but we shouldn't really use Exception as the lowest common denominator here
                        etype, value, tb = sys.exc_info()
                        error = traceback.format_exception_only(etype, value)[0].strip()
                        errorstring = "Error processing file: %s : %s" % (ffn, error)
                        filelog.write_error(errorstring)
                        continue
                        
                    tags = {}
                    trackart = None

                    if isinstance(kind, mutagen.flac.FLAC):
                        if len(kind.pictures) > 0:
                            trackart_offset, trackart_length = kind.find_picture_offset()
                            trackart = 'EMBEDDED_%s,%s' % (trackart_offset, trackart_length)
github sdushantha / soundcloud-dl / soundcloud-dl.py View on Github external
def tag(fname, title, artist, genre, arturl):

    try:
        tag = EasyID3(fname)

    except mutagen.id3.ID3NoHeaderError:
        tag = mutagen.File(fname, easy=True)
        tag.add_tags()

    tag['artist'] = artist
    tag['title'] = title

    # Giving the album the same name as
    # the title beacause
    # I cant find the album name
    tag['album'] = title
    tag['genre'] = genre
    tag.save()

    id3 = ID3(fname)

    imagename = str(title.replace("/", "\\")+"500x500.jpg")
github R-a-dio / Hanyuu-sama / hanyuu / streamer / audio / __init__.py View on Github external
def pop_file():
        try:
            filename = files.pop()
        except KeyError:
            return (None, None)
        if (filename.endswith('.flac') or
                filename.endswith('.mp3') or
                filename.endswith('.ogg')):
            try:
                meta = mutagen.File(filename, easy=True)
            except:
                meta = "No metadata available, because I errored."
            else:
                artist = meta.get('artist')
                title = meta.get('title')
                
                meta = u"{:s} - {:s}" if artist else u"{:s}"
                
                if artist:
                    artist = u", ".join(artist)
                if title:
                    title = u", ".join(title)
                meta = meta.format(artist, title)
            return (filename, meta)
        else:
            return pop_file()