#! /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.

Attributes:

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

tags -- metadata tags, if any

Each file format has different potential tags and stream

information.

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",

DeprecationWarning)

else:

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.add_tags()

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

else:

warnings.warn(

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

DeprecationWarning)

return self.tags.delete(filename)

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

"""Save metadata tags."""

if filename is None:

filename = self.filename

else:

warnings.warn(

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

DeprecationWarning)

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:

mimes.append(mime)

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

else:

from mutagen.id3 import ID3FileType

if easy:

from mutagen.mp3 import EasyMP3 as MP3

else:

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

else:

from mutagen.trueaudio import TrueAudio

from mutagen.wavpack import WavPack

if easy:

from mutagen.easymp4 import EasyMP4 as MP4

else:

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")

try:

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]

finally:

fileobj.close()

results = zip(results, options)

results.sort()

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

if score > 0: return Kind(filename)

else: return None

平时的笔记02:处理mp3的更多相关文章

  1. 平时的笔记02:处理fnmatch模块

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

  2. 软件测试之loadrunner学习笔记-02集合点

    loadrunner学习笔记-02集合点 集合点函数可以帮助我们生成有效可控的并发操作.虽然在Controller中多用户负载的Vuser是一起开始运行脚本的,但是由于计算机的串行处理机制,脚本的运行 ...

  3. 《30天自制操作系统》笔记(02)——导入C语言

    <30天自制操作系统>笔记(02)——导入C语言 进度回顾 在上一篇,记录了计算机开机时加载IPL程序(initial program loader,一个nas汇编程序)的情况,包括IPL ...

  4. 《The Linux Command Line》 读书笔记02 关于命令的命令

    <The Linux Command Line> 读书笔记02 关于命令的命令 命令的四种类型 type type—Indicate how a command name is inter ...

  5. 强化学习读书笔记 - 02 - 多臂老O虎O机问题

    # 强化学习读书笔记 - 02 - 多臂老O虎O机问题 学习笔记: [Reinforcement Learning: An Introduction, Richard S. Sutton and An ...

  6. JS自学笔记02

    JS自学笔记02 1.复习 js是一门解释性语言,遇到一行代码就执行一行代码 2.查阅mdn web文档 3.提示用户输入并接收,相比之下,alert只有提示的作用: prompt(字符串) 接收: ...

  7. 机器学习实战(Machine Learning in Action)学习笔记————02.k-邻近算法(KNN)

    机器学习实战(Machine Learning in Action)学习笔记————02.k-邻近算法(KNN) 关键字:邻近算法(kNN: k Nearest Neighbors).python.源 ...

  8. CS229 笔记02

    CS229 笔记02 公式推导 $ {\text {For simplicity, Let }} A, B, C \in {\Bbb {R}}^{n \times n}. $ ​ $ {\bf {\t ...

  9. OpenCV 学习笔记 02 使用opencv处理图像

    1 不同色彩空间的转换 opencv 中有数百种关于不同色彩空间的转换方法,但常用的有三种色彩空间:灰度.BRG.HSV(Hue-Saturation-Value) 灰度 - 灰度色彩空间是通过去除彩 ...

随机推荐

  1. C#生成带项目编号的Word段落

    using System; using Microsoft.Office.Interop.Word; using Word = Microsoft.Office.Interop.Word; names ...

  2. [置顶] Android安全机制分析

    Android系统是基于Linux内核开发的,因此,Android系统不仅保留和继承了Linux操作系统的安全机制,而且其系统架构的各个层次都有独特的安全特性[2] . 1. Linux内核层安全机制 ...

  3. [ES6] Generators

    Example 1: function *topicList(){ yield "ES2015"; yield "Semi-colons: good or bad?&qu ...

  4. 浅谈对JIT编译器的理解。

    1. 什么是Just In Time编译器? Hot Spot 编译 当 JVM 执行代码时,它并不立即开始编译代码.这主要有两个原因: 首先,如果这段代码本身在将来只会被执行一次,那么从本质上看,编 ...

  5. asp.net操作xml(增删查改)

    asp.net操作xml 1.xml文档Products.xml <?xml version="1.0" encoding="utf-8"?> &l ...

  6. android码农神器 偷懒工具 android懒人框架 LoonAndroid 3 讲解

    LoonAndroid 3.0 Loonandroid是一个注解框架,不涉及任何UI效果,目的是一个功能一个方法,以方法为最小颗粒度对功能进行拆解.把功能傻瓜化,简单化,去掉重复性的代码,隐藏复杂的实 ...

  7. JS时间日期

    JS获取当前时间 var myDate = new Date(); myDate.get[UTC]FullYear();    //获取完整的年份(4位,1970-????)myDate.get[UT ...

  8. mfc EDIT字体颜色

    改变Edit字体颜色: 1.CMyDlg类中添加成员变量: CBrush m_Brush; 2.OnInitDialog中初进行设置: m_brush.CreateSolidBrush(RGB(0,2 ...

  9. Sql server统计查询语句消耗时间

    1. set statistics time on go  xxxx go set statistics time off 2. DECLARE @begin dateTime DECLARE @en ...

  10. linux下查找文件和文件内容

    find /xxx -name "*" | xargs grep "某内容" /xxx表示路径,"*"表示在含有某关键字名字下的文件中查找, ...