#! /usr/bin/env python


# mutagen aims to be an all purpose media tagging library

# Copyright (C) 2005  Michael Urman


# This program is free software; you can redistribute it and/or modify

# it under the terms of version 2 of the GNU General Public License as

# published by the Free Software Foundation.


# $Id: __init__.py 4348 2008-12-02 02:41:15Z piman $


"""Mutagen aims to be an all purpose tagging library.

import mutagen.[format]

metadata = mutagen.[format].Open(filename)

metadata acts like a dictionary of tags in the file. Tags are generally a

list of string-like values, but may have additional methods available

depending on tag or format. They may also be entirely different objects

for certain keys, again depending on format.


version = (1, 20)

version_string = ".".join(map(str, version))

import warnings

import mutagen._util

class Metadata(object):

"""An abstract dict-like object.

Metadata is the base class for many of the tag objects in Mutagen.


def __init__(self, *args, **kwargs):

if args or kwargs:

self.load(*args, **kwargs)

def load(self, *args, **kwargs):

raise NotImplementedError

def save(self, filename=None):

raise NotImplementedError

def delete(self, filename=None):

raise NotImplementedError

class FileType(mutagen._util.DictMixin):

"""An abstract object wrapping tags and audio stream information.


info -- stream information (length, bitrate, sample rate)

tags -- metadata tags, if any

Each file format has different potential tags and stream


FileTypes implement an interface very similar to Metadata; the

dict interface, save, load, and delete calls on a FileType call

the appropriate methods on its tag data.


info = None

tags = None

filename = None

_mimes = ["application/octet-stream"]

def __init__(self, filename=None, *args, **kwargs):

if filename is None:

warnings.warn("FileType constructor requires a filename",



self.load(filename, *args, **kwargs)

def load(self, filename, *args, **kwargs):

raise NotImplementedError

def __getitem__(self, key):

"""Look up a metadata tag key.

If the file has no tags at all, a KeyError is raised.


if self.tags is None: raise KeyError, key

else: return self.tags[key]

def __setitem__(self, key, value):

"""Set a metadata tag.

If the file has no tags, an appropriate format is added (but

not written until save is called).


if self.tags is None:


self.tags[key] = value

def __delitem__(self, key):

"""Delete a metadata tag key.

If the file has no tags at all, a KeyError is raised.


if self.tags is None: raise KeyError, key

else: del(self.tags[key])

def keys(self):

"""Return a list of keys in the metadata tag.

If the file has no tags at all, an empty list is returned.


if self.tags is None: return []

else: return self.tags.keys()

def delete(self, filename=None):

"""Remove tags from a file."""

if self.tags is not None:

if filename is None:

filename = self.filename



"delete(filename=...) is deprecated, reload the file",


return self.tags.delete(filename)

def save(self, filename=None, **kwargs):

"""Save metadata tags."""

if filename is None:

filename = self.filename



"save(filename=...) is deprecated, reload the file",


if self.tags is not None:

return self.tags.save(filename, **kwargs)

else: raise ValueError("no tags in file")

def pprint(self):

"""Print stream information and comment key=value pairs."""

stream = "%s (%s)" % (self.info.pprint(), self.mime[0])

try: tags = self.tags.pprint()

except AttributeError:

return stream

else: return stream + ((tags and "\n" + tags) or "")

def add_tags(self):

raise NotImplementedError

def __get_mime(self):

mimes = []

for Kind in type(self).__mro__:

for mime in getattr(Kind, '_mimes', []):

if mime not in mimes:


return mimes

mime = property(__get_mime)

def File(filename, options=None, easy=False):

"""Guess the type of the file and try to open it.

The file type is decided by several things, such as the first 128

bytes (which usually contains a file type identifier), the

filename extension, and the presence of existing tags.

If no appropriate type could be found, None is returned.


if options is None:

from mutagen.asf import ASF

from mutagen.apev2 import APEv2File

from mutagen.flac import FLAC

if easy:

from mutagen.easyid3 import EasyID3FileType as ID3FileType


from mutagen.id3 import ID3FileType

if easy:

from mutagen.mp3 import EasyMP3 as MP3


from mutagen.mp3 import MP3

from mutagen.oggflac import OggFLAC

from mutagen.oggspeex import OggSpeex

from mutagen.oggtheora import OggTheora

from mutagen.oggvorbis import OggVorbis

if easy:

from mutagen.trueaudio import EasyTrueAudio as TrueAudio


from mutagen.trueaudio import TrueAudio

from mutagen.wavpack import WavPack

if easy:

from mutagen.easymp4 import EasyMP4 as MP4


from mutagen.mp4 import MP4

from mutagen.musepack import Musepack

from mutagen.monkeysaudio import MonkeysAudio

from mutagen.optimfrog import OptimFROG

options = [MP3, TrueAudio, OggTheora, OggSpeex, OggVorbis, OggFLAC,

FLAC, APEv2File, MP4, ID3FileType, WavPack, Musepack,

MonkeysAudio, OptimFROG, ASF]

if not options:

return None

fileobj = file(filename, "rb")


header = fileobj.read(128)

# Sort by name after score. Otherwise import order affects

# Kind sort order, which affects treatment of things with

# equals scores.

results = [(Kind.score(filename, fileobj, header), Kind.__name__)

for Kind in options]



results = zip(results, options)


(score, name), Kind = results[-1]

if score > 0: return Kind(filename)

else: return None

Usual notes 02: Handle mp3 More articles about

  1. Usual notes 02: Handle fnmatch modular

    # Copyright 2006 Joe Wreschnig## This program is free software; you can redistribute it and/or modif ...

  2. Software testing loadrunner Learning notes -02 Marshal Point

    loadrunner Learning notes -02 Marshal Point Set point functions can help us generate efficient and controllable concurrent operations . Although in Controller Multi user load in Vuser Start running scripts together , But because of the serial processing mechanism of the computer , Script run ...

  3. 《30 Self made operating system 》 note (02)—— Import C Language

    <30 Self made operating system > note (02)—— Import C Language Progress Review In the last article , Recorded the computer boot load IPL Program (initial program loader, One nas assembler ) The situation of , Include IPL ...

  4. 《The Linux Command Line》 Reading notes 02 Orders about orders

    <The Linux Command Line> Reading notes 02 Orders about orders Four types of commands type type—Indicate how a command name is inter ...

  5. Strengthen the study of reading notes - 02 - Dobby O The tiger O Machine problems

    # Strengthen the study of reading notes - 02 - Dobby O The tiger O Machine problems Learning notes : [Reinforcement Learning: An Introduction, Richard S. Sutton and An ...

  6. JS Self study notes 02

    JS Self study notes 02 1. review js It is an interpretive language , One line of code is executed when one line of code is encountered 2. Look up mdn web file 3. Prompt the user to input and receive , by comparison ,alert It's just a hint : prompt( character string ) receive : ...

  7. Machine learning practice (Machine Learning in Action) Learning notes ————02.k- Proximity algorithm (KNN)

    Machine learning practice (Machine Learning in Action) Learning notes ————02.k- Proximity algorithm (KNN) keyword : Proximity algorithm (kNN: k Nearest Neighbors).python. Source ...

  8. CS229 note 02

    CS229 note 02 Formula derivation $ {\text {For simplicity, Let }} A, B, C \in {\Bbb {R}}^{n \times n}. $ ​ $ {\bf {\t ...

  9. OpenCV Learning notes 02 Use opencv Process images

    1 The conversion of different color spaces opencv There are hundreds of different color space conversion methods , But there are three common color spaces : Grayscale .BRG.HSV(Hue-Saturation-Value) Grayscale - Gray color space is by removing color ...

Random recommendation

  1. MediaRecorder Class introduction

    audiocallbackvideojavadescriptorencoding Catalog (?)[+] Found one MediaRecorder Class introduction to share with you . Mediarecorder Class in the introduction of the official website and in ...

  2. openstack Distributed installation

    One . keystone Install notes For the first time contact openstack, I'm not very satisfied after trying the stand-alone deployment , Start with distributed deployment , Mainly according to openstack From the installation tutorial on the official website , I installed the latest I edition . With ...

  3. Nubia Z5S Based on the official H207/4.4 Kernel Mokee4.4.4 RC3.2 (2014.7.31 Repair breathing lights ( Can light still can't breathe ))

    Special thanks yun3195 and   touch on lightly Yhw  Help test Please be sure to indicate this link address when posting : http://blog.csdn.net/syhost/article/details/36444259 this ROM ...

  4. UIButton Summary of common attributes ( Editing ...)

    Button It's very pornographic and violent , The text can be displayed , It can also display pictures , You can also adjust the position of internal pictures and text at any time , There's a lot of use . (1) There are four common states of buttons : normal( Normal state ) By default (Default) The corresponding enumeration ...

  5. python in __call__() Method usage

    __call__() Usage of __call__() Methods enable instance objects of a class to , Called like a function : >>> >>> class A(object): def __call_ ...

  6. 《Mysql Technology insider ,Innodb Storage engine 》—— thing

    thing The operations in things are either successful or not done , This is the purpose of things , It is also one of the important characteristics of the thing model and file system . Flat things (Flat Transactions) All operations are at the same level , Either do it all, or do it all, or roll it all back , nothing ...

  7. Cloud database Redis edition 256M Double hot standby

    Cloud database Redis Version is compatible Redis Agreement standard . Provide persistent cache database service , Based on high reliable dual hot standby architecture : all-new 256M Small size , Suitable for high QPS. Small data business , And support free full migration , Perfect for individual developers ...

  8. Luogu P4528 [CTSC2008] Totems

    Luogu P4528 [CTSC2008] Totems Divine topic orz. Make an appointment first abcd Express \(1\leq A<B<C<D\leq n\), and \(y_a,y_b,y_c,y_d\) My ranking is just \( ...

  9. ubuntu16.04 The system is streamlined

    ubuntu16.04 The system is streamlined One . Update system apt-get update apt-get dist-upgrade Two . View all cores sudo dpkg --get-selections |grep ...

  10. liunx vim Common operation command

    vim Common operation command vim abc // Open the file , Or create a new file vim +3 abc // Open the file and jump to the third line vim +/hello // Open the file and jump to the first appearance hello The location of vim ...