Python mutagen.File() Examples

The following are 23 code examples of mutagen.File(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mutagen , or try the search function .
Example #1
Source File: freesound.py    From Mash-Cogs with GNU General Public License v3.0 6 votes vote down vote up
def add_metadata(self, file, sound):
        # "sound" requires a "freesound_client.get_sound" object
        # http://wiki.hydrogenaud.io/index.php?title=APE_key
        try:
            # Write it
            audio = FLAC(file)
            audio["title"] = sound.name
            audio["Artist"] = sound.username
            audio["Comment"] = sound.description
            audio["Publisher"] = "freesound.org"
            audio["File"] = sound.url
            # Save it
            audio.pprint()
            audio.save()
            # Read it
            file_info = mutagen.File(file)
            log.debug("Result metadata update:")
            log.debug(file_info)
            return file_info
        except Exception as e:
            log.debug(e)
            return False 
Example #2
Source File: utils.py    From bard with GNU General Public License v3.0 6 votes vote down vote up
def removeAllTags(filelike, recurse=True):
    try:
        filelike.seek(0)
        id3 = mutagen.id3.ID3(filelike)
    except mutagen.id3._util.ID3NoHeaderError:
        pass
    else:
        filelike.seek(0)
        id3.delete(filelike)

    filelike.seek(0)
    mutagenFile = mutagen.File(filelike)
    # print(type(mutagenFile), filelike.name)

    if isinstance(mutagenFile, mutagen.flac.FLAC) and mutagenFile.pictures:
        mutagenFile.clear_pictures()
        filelike.seek(0)
        mutagenFile.save(filelike, padding=lambda x: 0)

    filelike.seek(0)
    if mutagenFile:
        mutagenFile.delete(filelike) 
Example #3
Source File: utils.py    From bard with GNU General Public License v3.0 6 votes vote down vote up
def removeAllTagsFromPath(path):
    # subprocess.check_output(['id3v2', '--delete-all', path])
    mutagenFile = mutagen.File(path)
    print(type(mutagenFile), path)

    if isinstance(mutagenFile, mutagen.flac.FLAC):
        mutagenFile.clear_pictures()
        mutagenFile.delete(path)
        # mutagenFile.save(path, deleteid3=True, padding=lambda x: 0)
        return
    elif isinstance(mutagenFile, mutagen.id3.ID3FileType):
        mutagenFile.delete(path)
        return
    elif isinstance(mutagenFile, mutagen.apev2.APEv2File):
        mutagenFile.delete(path)
        return

    mutagenFile.delete(path) 
Example #4
Source File: song.py    From bard with GNU General Public License v3.0 6 votes vote down vote up
def getCoverImage(self):
        path = self.path()
        directory = os.path.dirname(path)
        for cover in ['cover.jpg', 'cover.png']:
            coverfilename = os.path.join(directory, cover)
            if os.path.exists(coverfilename):
                return coverfilename

        try:
            metadata = self.metadata
        except AttributeError:
            try:
                metadata = mutagen.File(path)
            except mutagen.mp3.HeaderNotFoundError as e:
                print("Error reading %s:" % path, e)
                return None

        try:
            image = extractFrontCover(metadata)
        except OSError:
            print('Error extracting image from %s' % path)
            return None

        return image 
Example #5
Source File: recurse.py    From sacad with Mozilla Public License 2.0 6 votes vote down vote up
def embed_album_art(cover_filepath, audio_filepaths):
  """ Embed album art into audio files. """
  with open(cover_filepath, "rb") as f:
    cover_data = f.read()

  for filepath in audio_filepaths:
    mf = mutagen.File(filepath)
    if (isinstance(mf.tags, mutagen._vorbis.VComment) or
            isinstance(mf, mutagen.ogg.OggFileType)):
      picture = mutagen.flac.Picture()
      picture.data = cover_data
      picture.type = mutagen.id3.PictureType.COVER_FRONT
      picture.mime = "image/jpeg"
      encoded_data = base64.b64encode(picture.write())
      mf["metadata_block_picture"] = encoded_data.decode("ascii")
    elif (isinstance(mf.tags, mutagen.id3.ID3) or
          isinstance(mf, mutagen.id3.ID3FileType)):
      mf.tags.add(mutagen.id3.APIC(mime="image/jpeg",
                                   type=mutagen.id3.PictureType.COVER_FRONT,
                                   data=cover_data))
    elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
          isinstance(mf, mutagen.mp4.MP4)):
      mf["covr"] = [mutagen.mp4.MP4Cover(cover_data,
                                         imageformat=mutagen.mp4.AtomDataType.JPEG)]
    mf.save() 
Example #6
Source File: mutagen_inspect.py    From bugatsinho.github.io with GNU General Public License v3.0 6 votes vote down vote up
def main(argv):
    from mutagen import File

    parser = OptionParser()
    parser.add_option("--no-flac", help="Compatibility; does nothing.")
    parser.add_option("--no-mp3", help="Compatibility; does nothing.")
    parser.add_option("--no-apev2", help="Compatibility; does nothing.")

    (options, args) = parser.parse_args(argv[1:])
    if not args:
        raise SystemExit(parser.print_help() or 1)

    for filename in args:
        print_(u"--", filename)
        try:
            print_(u"-", File(filename).pprint())
        except AttributeError:
            print_(u"- Unknown file type")
        except Exception as err:
            print_(text_type(err))
        print_(u"") 
Example #7
Source File: utils.py    From spotify-ripper with MIT License 6 votes vote down vote up
def is_partial(audio_file, track):
    args = get_args()
    if (args.partial_check == "none"):
        return False

    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

    audio_file_dur = audio_file_duration(audio_file)

    # for 'weak', give a ~1.5 second wiggle-room
    if (args.partial_check == "strict"):
        return (audio_file_dur is None or
            track.duration > (audio_file_dur * 1000))
    else:
        return (audio_file_dur is not None and
            (track.duration - 1500) > (audio_file_dur * 1000))


# borrowed from eyeD3 
Example #8
Source File: bard.py    From bard with GNU General Public License v3.0 6 votes vote down vote up
def fixMtime(self):
        collection = getMusic()
        count = 0
        for song in collection:
            if not song.mtime():
                try:
                    mtime = os.path.getmtime(song.path())
                except os.FileNotFoundError:
                    print('File %s not found: removing from db' % song.path())
                    MusicDatabase.removeSong(song)
                    continue

                if not config['immutableDatabase']:
                    c = MusicDatabase.getCursor()
                    sql = text('UPDATE songs set mtime = :mtime '
                               'WHERE id = :id')
                    c.execute(sql.bindparams(mtime=mtime, id=song.id))
                    count += 1
                    if count % 10:
                        MusicDatabase.commit()
                print('Fixed %s' % song.path())
            else:
                print('%s already fixed' % song.path())
        MusicDatabase.commit() 
Example #9
Source File: bard.py    From bard with GNU General Public License v3.0 5 votes vote down vote up
def checkSongsExistenceInPath(self, song, callback=None):
        if not os.path.exists(song.path()):
            if os.path.lexists(song.path()):
                print('Broken symlink at %s' % song.path())
            else:
                print('File not found: %s' % song.path())

                if callback:
                    callback(song) 
Example #10
Source File: dataprocessor.py    From rnn-speech with MIT License 5 votes vote down vote up
def _add_audio_length_on_file(audio_file, text, _length):
        file = mutagen.File(audio_file)
        try:
            length = file.info.length
        except AttributeError:
            # In case the type was not recognized by mutagen
            logging.warning("Audio file incorrect : %s", audio_file)
            length = 0
        return [audio_file, text, length] 
Example #11
Source File: bard.py    From bard with GNU General Public License v3.0 5 votes vote down vote up
def fixTags(self, args):
        for path in args:
            if not os.path.isfile(path):
                print('"%s" is not a file. Skipping.' % path)
                continue

            mutagenFile = mutagen.File(path)
            fixTags(mutagenFile)

            if (MusicDatabase.isSongInDatabase(path) and
               not path.startswith('/tmp/')):
                self.addSong(path) 
Example #12
Source File: musictools_tests.py    From MusicTools with MIT License 5 votes vote down vote up
def test_add_album_art():

    musictools.add_album_art(location, albumart)
    tags = File(location)
 
    assert 'APIC:Cover' in tags.keys() != None 
Example #13
Source File: freesound.py    From Mash-Cogs with GNU General Public License v3.0 5 votes vote down vote up
def copy_move_tree(self, source, destination):
        ex = False
        # Copy to new path
        try:
            await self.bot.say("`Moving File:  {} to {}`".format(source, destination))
            dir = DIR_TMP+"\\"+n
            #print(dir)
            shutil.copytree(d, dir)
            cp = True
        except OSError as e:
            if sys.platform.startswith('win'):
                if isinstance(e, WindowsError) and e.winerror == 103:
                    await self.bot.say("WinError during copy code: {}".format(str(n)))
                    log.debug('uses Windows special name (%s)' % e)
                if isinstance(e, WindowsError) and e.winerror == 183:
                    await self.bot.say("WinError during copy code file/dir already exist: {}".format(str(n)))
                    log.debug('uses Windows special name file/dir exist (%s)' % n)
                # etc...
            ex = True
        # Burn the old folder
        if cp:
            try:
                await self.bot.say("`Delete {} from Import`".format(source))
                shutil.rmtree(source)
            except OSError as e:
                if sys.platform.startswith('win'):
                    log.debug(e)
                if isinstance(e, WindowsError) and e.winerror == 3:
                    await self.bot.say(" File/dir Not found: {}".format(str(n)))
                    log.debug('uses Windows special name (%s)' % e)
                # etc....
                ex = True
        if ex:
            print(":(")
            return 
Example #14
Source File: infoEditor.py    From BilibiliTools with Apache License 2.0 5 votes vote down vote up
def initialize(file):
        audio = mutagen.File(file)
        if (isinstance(audio, MP4)):
            return mp4Editor(file)
        if (isinstance(audio, MP3)):
            return mp3Editor(file) 
Example #15
Source File: common.py    From QMusic with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_audio_length(path):        
    try:
        audio = MutagenFile(path, FORMATS)
        if audio is not None:
            return int(audio.info.length) * 1000
        return 0
    except:
        return 0 
Example #16
Source File: common.py    From QMusic with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_audio_length(path):
    try:
        audio = MutagenFile(path, FORMATS)
        if audio is not None:
            return int(audio.info.length) * 1000
        return 0
    except:
        return 0 
Example #17
Source File: recurse.py    From sacad with Mozilla Public License 2.0 4 votes vote down vote up
def get_file_metadata(audio_filepath):
  """ Get a Metadata object for this file or None. """
  try:
    mf = mutagen.File(audio_filepath)
  except Exception:
    return
  if mf is None:
    return

  # artist
  for key in ("albumartist", "artist",  # ogg
              "TPE1", "TPE2",  # mp3
              "aART", "\xa9ART"):  # mp4
    try:
      val = mf.get(key, None)
    except ValueError:
      val = None
    if val is not None:
      artist = val[-1]
      break
  else:
    return

  # album
  for key in ("_album", "album",  # ogg
              "TALB",  # mp3
              "\xa9alb"):  # mp4
    try:
      val = mf.get(key, None)
    except ValueError:
      val = None
    if val is not None:
      album = val[-1]
      break
  else:
    return

  # album art
  if isinstance(mf.tags, mutagen._vorbis.VComment):
    has_embedded_cover = "metadata_block_picture" in mf
  elif isinstance(mf.tags, mutagen.id3.ID3):
    has_embedded_cover = any(map(operator.methodcaller("startswith", "APIC:"), mf.keys()))
  elif isinstance(mf.tags, mutagen.mp4.MP4Tags):
    has_embedded_cover = "covr" in mf
  else:
    return

  return Metadata(artist, album, has_embedded_cover) 
Example #18
Source File: zynthian_gui_audio_recorder.py    From zynthian-ui with GNU General Public License v3.0 4 votes vote down vote up
def get_filelist(self, src_dir):
		res = {}
		for f in sorted(os.listdir(src_dir)):
			fpath = join(src_dir, f)
			fname = f[:-4]
			fext = f[-4:].lower()
			if isfile(fpath) and fext in ('.wav', '.mp3', '.ogg'):
				if fname in res:
					if fext=='.wav':
						res[fname]['ext'] = fext
					elif fext=='.ogg' and res[fname]['ext']!='.wav':
						res[fname]['ext'] = fext
				else:	
					res[fname] = {
						'fpath': fpath,
						'ext': fext
					}

		for fname in res:
			try:
				res[fname]['length'] = mutagen.File(res[fname]['fpath']).info.length
			except Exception as e:
				res[fname]['length'] = 0
				logging.warning(e)

		return res 
Example #19
Source File: file.py    From botamusique with MIT License 4 votes vote down vote up
def _get_info_from_tag(self):
        match = re.search(r"(.+)\.(.+)", self.uri())
        assert match is not None

        file_no_ext = match[1]
        ext = match[2]

        try:
            im = None
            path_thumbnail = file_no_ext + ".jpg"
            if os.path.isfile(path_thumbnail):
                im = Image.open(path_thumbnail)

            if ext == "mp3":
                # title: TIT2
                # artist: TPE1, TPE2
                # album: TALB
                # cover artwork: APIC:
                tags = mutagen.File(self.uri())
                if 'TIT2' in tags:
                    self.title = tags['TIT2'].text[0]
                if 'TPE1' in tags:  # artist
                    self.artist = tags['TPE1'].text[0]

                if im is None:
                    if "APIC:" in tags:
                        im = Image.open(BytesIO(tags["APIC:"].data))

            elif ext == "m4a" or ext == "m4b" or ext == "mp4" or ext == "m4p":
                # title: ©nam (\xa9nam)
                # artist: ©ART
                # album: ©alb
                # cover artwork: covr
                tags = mutagen.File(self.uri())
                if '©nam' in tags:
                    self.title = tags['©nam'][0]
                if '©ART' in tags:  # artist
                    self.artist = tags['©ART'][0]

                if im is None:
                    if "covr" in tags:
                        im = Image.open(BytesIO(tags["covr"][0]))

            if im:
                self.thumbnail = self._prepare_thumbnail(im)
        except:
            pass

        if not self.title:
            self.title = os.path.basename(file_no_ext) 
Example #20
Source File: repair.py    From MusicNow with MIT License 4 votes vote down vote up
def fix_music(file_name):
    '''
    Searches for '.mp3' files in directory (optionally recursive)
    and checks whether they already contain album art and album name tags or not.
    '''

    setup()

    if not Py3:
        file_name = file_name.encode('utf-8')

    tags = File(file_name)

    log.log(file_name)
    log.log('> Adding metadata')

    try:
        artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
            file_name)  # Try finding details through spotify

    except Exception:
        artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
            file_name)  # Use bad scraping method as last resort

    try:
        log.log_indented('* Trying to extract album art from Google.com')
        albumart = albumsearch.img_search_google(artist+' '+album)
    except Exception:
        log.log_indented('* Trying to extract album art from Bing.com')
        albumart = albumsearch.img_search_bing(artist+' '+album)

    if match_bool:
        add_albumart(albumart, file_name)
        add_details(file_name, song_name, artist, album, lyrics)

        try:
            rename(file_name, artist+' - '+song_name+'.mp3')
        except Exception:
            log.log_error("Couldn't rename file")
            pass
    else:
        log.log_error(
            "* Couldn't find appropriate details of your song", indented=True)

    log.log("Match score: %s/10.0" % round(score * 10, 1))
    log.log(LOG_LINE_SEPERATOR)
    log.log_success() 
Example #21
Source File: soundcloud-downloader.py    From soundcloud-page-downloader with GNU General Public License v2.0 4 votes vote down vote up
def download_file(download_url, artist_name, artist_friendlyname,
                  song_name, song_genre):
    directory = os.path.join('soundcloud-downloads', artist_friendlyname)
    if not os.path.exists(directory):
        os.makedirs(directory)

    file_name = "soundcloud-downloads/{}/{}.mp3".format(artist_friendlyname,
                                                        song_name)
    # urllib2 file download implementation by PabloG @ StackOverflow -
    # http://stackoverflow.com/a/22776
    u = urllib2.urlopen(download_url)
    f = open(file_name, 'wb')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: {} (Bytes: {})".format(song_name, file_size)

    file_size_dl = 0
    block_sz = 8192
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break

        file_size_dl += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (
            file_size_dl, file_size_dl * 100. / file_size)
        status = status + chr(8) * (len(status) + 1)
        print status,

    f.close()

    try:
        meta = EasyID3(file_name)
    except mutagen.id3.ID3NoHeaderError:
        meta = mutagen.File(file_name, easy=True)
        meta.add_tags()

    meta['title'] = song_name
    meta['artist'] = artist_name
    meta['genre'] = song_genre
    meta.save() 
Example #22
Source File: database.py    From kawaii-player with GNU General Public License v3.0 4 votes vote down vote up
def update_on_start_music_db(self, music_db, music_file, music_file_bak,
                                 update_progress_show=None):
        m_files = self.import_music(music_file, music_file_bak)
        try:
            conn = sqlite3.connect(music_db)
            cur = conn.cursor()
            cur.execute('SELECT Path, Modified FROM Music')
            rows = cur.fetchall()
            conn.commit()
            conn.close()
        except Exception as e:
            print(e, '--database-corrupted--21369---')
            return 0
        m_files_old = []
        for i in rows:
            j = i[0]+'	'+(str(i[1])).split('.')[0]
            m_files_old.append(str(j))
        
        l1 = len(m_files)
        l2 = len(m_files_old)
        m = list(set(m_files)-set(m_files_old))+list(set(m_files_old)-set(m_files))
        m_files.sort()
        m_files_old.sort()
        print("************")

        print("_______________")
        self.logger.info(m)
        self.logger.info(m.sort())
        self.logger.info(len(m))
        self.logger.info(len(m_files))
        self.logger.info(len(m_files_old))
        conn = sqlite3.connect(music_db)
        cur = conn.cursor()
        for k in m:
            j = k.split('	')
            i = str(j[0])

            cur.execute('SELECT Path FROM Music Where Path=?', (i, ))
            rows = cur.fetchall()

            if os.path.exists(i) and (k in m_files) and not rows:
                w = self.get_tag_lib(i)
                cur.execute('INSERT INTO Music VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', w)
            elif os.path.exists(i) and rows and (k in m_files):
                print("File Modified")
                cur.execute('Delete FROM Music Where Path=?', (i, ))
                self.logger.info('Deleting File From Database : '+i)
                w = self.get_tag_lib(i)
                cur.execute('INSERT INTO Music VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', w)
            elif not os.path.exists(i) and rows:
                cur.execute('Delete FROM Music Where Path=?', (i, ))
                self.logger.info('Deleting File From Database : '+i)
            elif os.path.exists(i) and not rows:
                cur.execute('Delete FROM Music Where Path=?', (i, ))
                self.logger.info('Deleting File From Database : '+i)

        conn.commit()
        conn.close() 
Example #23
Source File: mediafile.py    From mediafile with MIT License 4 votes vote down vote up
def __init__(self, path, id3v23=False):
        """Constructs a new `MediaFile` reflecting the file at path. May
        throw `UnreadableFileError`.

        By default, MP3 files are saved with ID3v2.4 tags. You can use
        the older ID3v2.3 standard by specifying the `id3v23` option.
        """
        self.path = path

        self.mgfile = mutagen_call('open', path, mutagen.File, path)

        if self.mgfile is None:
            # Mutagen couldn't guess the type
            raise FileTypeError(path)
        elif type(self.mgfile).__name__ in ['M4A', 'MP4']:
            info = self.mgfile.info
            if info.codec and info.codec.startswith('alac'):
                self.type = 'alac'
            else:
                self.type = 'aac'
        elif type(self.mgfile).__name__ in ['ID3', 'MP3']:
            self.type = 'mp3'
        elif type(self.mgfile).__name__ == 'FLAC':
            self.type = 'flac'
        elif type(self.mgfile).__name__ == 'OggOpus':
            self.type = 'opus'
        elif type(self.mgfile).__name__ == 'OggVorbis':
            self.type = 'ogg'
        elif type(self.mgfile).__name__ == 'MonkeysAudio':
            self.type = 'ape'
        elif type(self.mgfile).__name__ == 'WavPack':
            self.type = 'wv'
        elif type(self.mgfile).__name__ == 'Musepack':
            self.type = 'mpc'
        elif type(self.mgfile).__name__ == 'ASF':
            self.type = 'asf'
        elif type(self.mgfile).__name__ == 'AIFF':
            self.type = 'aiff'
        elif type(self.mgfile).__name__ == 'DSF':
            self.type = 'dsf'
        else:
            raise FileTypeError(path, type(self.mgfile).__name__)

        # Add a set of tags if it's missing.
        if self.mgfile.tags is None:
            self.mgfile.add_tags()

        # Set the ID3v2.3 flag only for MP3s.
        self.id3v23 = id3v23 and self.type == 'mp3'