Home
huangjiahua~~我自己的世界
用 python-mutagen 转换 mp3 标签编码 

Advertisement

Customize
10th-Sep-2006 05:26 pm
logo-1
http://www.hiweed.com/node/111
先安装 python-mutagen包,执行

sudo apt-get install python-mutagen

在有 mp3 的目录下执行编码转换

find . -iname "*.mp3" -execdir mid3iconv -e GBK {} \;

这会转换当前目录其子目录中的 mp3 文件标签编码为正确的 utf8 。



如果你系统里安装了 python-mutagen , 却没有 /usr/bin/mid3iconv ,

那么试试手工建立 /usr/bin/mid3iconv 这个文件吧,
内容如下:
#!/usr/bin/python
#
# file:  /usr/bin/mid3iconv
#
# ID3iconv is a Java based ID3 encoding convertor, here's the Python version.
# Copyright 2006 Emfox Zhou <emfoxzhou@gmail.com>
#
# 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.
#

import os
import sys
import locale

from optparse import OptionParser

VERSION = (0, 1)

def isascii(string):
    return not string or min(string) < '\x127'

class ID3OptionParser(OptionParser):
    def __init__(self):
        mutagen_version = ".".join(map(str, mutagen.version))
        my_version = ".".join(map(str, VERSION))
        version = "mid3iconv %s\nUses Mutagen %s" % (
            my_version, mutagen_version)
        return OptionParser.__init__(
            self, version=version,
            usage="%prog [OPTION] [FILE]...",
            description=("Mutagen-based replacement the id3iconv utility, "
                         "which converts ID3 tags from legacy encodings "
                         "to Unicode and stores them using the ID3v2 format."))

    def format_help(self, *args, **kwargs):
        text = OptionParser.format_help(self, *args, **kwargs)
        return text + "\nFiles are updated in-place, so use --dry-run first.\n"

def update(options, filenames):
    encoding = options.encoding or locale.getpreferredencoding()
    verbose = options.verbose
    noupdate = options.noupdate
    force_v1 = options.force_v1
    remove_v1 = options.remove_v1

    def conv(uni):
        return uni.encode('iso-8859-1').decode(encoding)

    for filename in filenames:
        if verbose != "quiet":
            print "Updating", filename

        if has_id3v1(filename) and not noupdate and force_v1:
            mutagen.id3.delete(filename, False, True)

        try: id3 = mutagen.id3.ID3(filename)
        except mutagen.id3.ID3NoHeaderError:
            if verbose != "quiet":
                print "No ID3 header found; skipping..."
            continue
        except Exception, err:
            if verbose != "quiet":
                print str(err)
            continue

        for tag in filter(lambda t: t.startswith("T"), id3):
            if tag == "TDRC": # non-unicode field
                continue

            frame = id3[tag]

            try:
                text = map(conv, frame.text)
            except (UnicodeError, LookupError):
                continue
            else:
                frame.text = text
                if min(map(isascii, text)):
                    frame.encoding = 3
                else:
                    frame.encoding = 1

        enc = locale.getpreferredencoding()
        if verbose == "debug":
            print id3.pprint().encode(enc, "replace")

        if not noupdate:
            if remove_v1: id3.save(filename, v1=False)
            else: id3.save(filename)

def has_id3v1(filename):
    f = open(filename, 'rb+')
    try: f.seek(-128, 2)
    except IOError: pass
    else: return (f.read(3) == "TAG")

def main(argv):
    parser = ID3OptionParser()
    parser.add_option(
        "-e", "--encoding", metavar="ENCODING", action="store",
        type="string", dest="encoding",
        help=("Specify original tag encoding (default is %s)" %(
        locale.getpreferredencoding())))
    parser.add_option(
        "-p", "--dry-run", action="store_true", dest="noupdate",
        help="Do not actually modify files")
    parser.add_option(
        "--force-v1", action="store_true", dest="force_v1",
        help="Use an ID3v1 tag even if an ID3v2 tag is present")
    parser.add_option(
        "--remove-v1", action="store_true", dest="remove_v1",
        help="Remove v1 tag after processing the files")
    parser.add_option(
        "-q", "--quiet", action="store_const", dest="verbose",
        const="quiet", help="Only output errors")
    parser.add_option(
        "-d", "--debug", action="store_const", dest="verbose",
        const="debug", help="Output updated tags")

    for i, arg in enumerate(sys.argv):
        if arg == "-v1": sys.argv[i] = "--force-v1"
        elif arg == "-removev1": sys.argv[i] = "--remove-v1"

    (options, args) = parser.parse_args(argv[1:])

    if args:
        update(options, args)
    else:
        parser.print_help()

if __name__ == "__main__":
    try: import mutagen, mutagen.id3
    except ImportError:
        # Run out of tools/
        sys.path.append(os.path.abspath("../"))
        import mutagen, mutagen.id3
    main(sys.argv)




Comments 
25th-Sep-2006 04:44 pm (UTC)
Anonymous
奇怪,装了python-mutagen这个包,却没有mid3iconv这个命令
8th-May-2008 01:07 pm (UTC) - ThoyQnLrrY
Anonymous
7m4rbU hi nice site thanks http://peace.com
9th-May-2008 06:03 am (UTC) - nwgWlCeEXacegWvoje
Anonymous
lrET8q fw831f64td9glse934dkjga
5th-Jun-2008 09:26 am (UTC) - DTzpTRWJPovbwe
Anonymous
ES0bQ4 fdf043hj93jkfjw845qgtj6fqp
14th-Jun-2008 07:47 pm (UTC) - SDTdxfvJoJ
Anonymous
It's serious http://google.us/group/llteens preteen sexy models :(((
23rd-Jun-2008 11:16 am (UTC) - HpWwBhKZjkPXOWY
Anonymous
cCOkmm dfv078fnw8f934ndvkg2l
1st-Jul-2008 01:32 pm (UTC) - eIHiDfPGURjC
Anonymous
I love this site california internet access cheap hotel in poughkeepsie new york tjlfey
2nd-Jul-2008 01:23 am (UTC) - xqLqnrlNHMpTLQewB
Anonymous
Wonderfull great site beach and hotels cheap hotels around disney world djg
2nd-Jul-2008 10:45 am (UTC) - xDEHpTphpKAvXaoNg
Anonymous
perfect design thanks hotel rooms in charlston sc street in new york noted for cheap hotels and %-P
2nd-Jul-2008 11:34 am (UTC) - FjiHqNjNBTIqzSCIy
Anonymous
Best Site good looking rate orleans hotel las vegas cheap vegas 8-))
2nd-Jul-2008 03:14 pm (UTC) - SuezTWOcKqYMWLVN
Anonymous
Cool site goodluck :) frankenmuth michigan cheap hotels granbury texas iqngje
9th-Jul-2008 03:39 pm (UTC) - ZPEvyHgZSmqHD
Anonymous
4yIV8U preved krosav4eg
4th-Aug-2008 03:05 am (UTC) - McAXYSVZItrwwdVjxu
Anonymous
far.txt;3;3
4th-Aug-2008 05:34 am (UTC) - WEflFICRVyjTUlwdPy
Anonymous
far.txt;3;3
4th-Aug-2008 08:14 am (UTC) - VFfuNRZQZwePdBOlC
Anonymous
far.txt;3;3
12th-Sep-2008 11:24 am (UTC) - ybvqEqhcWOzFXHFZka
Anonymous
Palin Links Iraq & 9/11 | McCain: Link Is 'Naive' voices.washingtonpost.com/the-trail/2008/09/11/palin_endorses_idea_mccain_cal.html
6th-Oct-2008 06:00 pm (UTC) - KPlZRsWGyOtGcp
Anonymous
comment2,
3rd-Feb-2009 11:08 pm (UTC) - gUUaQdHMneZIxtA
Anonymous
out.txt;3;3
23rd-Apr-2009 05:40 am (UTC) - dndLnKqThAOaWCTX
Anonymous
lrmX0P http://google.com

Advertisement

Customize
This page was loaded Jul 6th 2009, 3:49 am GMT.