#! /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. python高级编程之我不测试

    # -*- coding: utf-8 -*-__author__ = 'Administrator'#测试驱动开发(高级编程处学习,第11章)#测试驱动开发也叫TDD, 是制造高质量软件的一种简单技 ...

  2. 【leetcode】Merge k Sorted Lists(按大小顺序连接k个链表)

    题目:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity ...

  3. [转] iOS使用NSMutableAttributedString 实现富文本(不同颜色字体、下划线等)

    转自: 在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求.之前在网上找了一些资料,有的是重绘UILabel的textLayer,有的是用html5实现的,都 ...

  4. Web Api 跨域解决方案

    一.跨域问题的由来 同源策略:出于安全考虑,浏览器会限制脚本中发起的跨站请求,浏览器要求JavaScript或Cookie只能访问同域下的内容. 正是由于这个原因,我们不同项目之间的调用就会被浏览器阻 ...

  5. ASP.NET入门 - 错误和异常处理

    当发生错误时,应该向用户提供一个友好的界面,可以屏蔽详细技术信息,也有助提升用户体验,这时就用到了异常处理. 错误类型: 语法错误:因缺少关键字,符号,或其他不正确代码所产生的错误,无法通过编译. 逻 ...

  6. WebApi2官网学习记录---OData中的查询

    EMD安全 查询语法是基于entity data model(EDM),不是基于底层的model类型,可以从EDM排除一个属性,这样这个属性在client就不能被查询了. 有两种方式可以从EDM中排除 ...

  7. Asp.Net HttpApplication请求管道与Session(一)

    1.请求处理顺序执行事件 /********************请求处理顺序执行事件**********************/ /// <summary> /// 请求入站 /// ...

  8. bug调试大全

    http://www.jianshu.com/p/9fc9fd89bfee http://www.cocoachina.com/ios/20150929/13598.html

  9. iOS_SN_Socket - AsyncSocket

    转载文章,原地址:http://yimouleng.com/2015/02/04/Socket-AsyncSocket/ 一.前言 公司的项目用到了Socket编程,之前在学习的过程当中,用到的更多的 ...

  10. [总结] Stack: Java V.S. C++

    小结一下Stack 的主要API操作. 在c++ 和 java 中,stack 的操作几乎相同,只有查询栈顶元素一项操作的名称不同 (top() v.s. peek()) . 此外,在构造函数中,Ja ...