使用 Python 访问 MP3 元数据

发布于 2024-07-04 04:06:35 字数 1452 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

◇流星雨 2024-07-11 04:06:36

我之前曾使用 mutagen 编辑媒体文件中的标签。 mutagen 的好处是它可以处理其他格式,例如 mp4、FLAC 等。我使用这个 API 编写了几个脚本,并取得了很大的成功。

I've used mutagen to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.

淡墨 2024-07-11 04:06:36

eyed3 的一个问题是,对于常见的 MP3 文件,它会抛出 NotImplementedError("Unable to write ID3 v2.2")

根据我的经验,mutagenEasyID3 工作更可靠。 示例:

from mutagen.easyid3 import EasyID3

audio = EasyID3("example.mp3")
audio['title'] = u"Example Title"
audio['artist'] = u"Me"
audio['album'] = u"My album"
audio['composer'] = u"" # clear
audio.save()

所有其他标签都可以通过这种方式访问​​并保存,这将满足大多数目的。 更多信息请参阅Mutagen 教程

A problem with eyed3 is that it will throw NotImplementedError("Unable to write ID3 v2.2") for common MP3 files.

In my experience, the mutagen class EasyID3 works more reliably. Example:

from mutagen.easyid3 import EasyID3

audio = EasyID3("example.mp3")
audio['title'] = u"Example Title"
audio['artist'] = u"Me"
audio['album'] = u"My album"
audio['composer'] = u"" # clear
audio.save()

All other tags can be accessed this way and saved, which will serve most purposes. More information can be found in the Mutagen Tutorial.

给妤﹃绝世温柔 2024-07-11 04:06:36

您需要的是 ID3 模块。 它非常简单,并且能够满足您的需求。 只需将 ID3.py 文件复制到您的 site-packages 目录中,您就可以执行如下操作:

from ID3 import *
try:
  id3info = ID3('file.mp3')
  print id3info
  # Change the tags
  id3info['TITLE'] = "Green Eggs and Ham"
  id3info['ARTIST'] = "Dr. Seuss"
  for k, v in id3info.items():
    print k, ":", v
except InvalidTagError, message:
  print "Invalid ID3 tag:", message

What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:

from ID3 import *
try:
  id3info = ID3('file.mp3')
  print id3info
  # Change the tags
  id3info['TITLE'] = "Green Eggs and Ham"
  id3info['ARTIST'] = "Dr. Seuss"
  for k, v in id3info.items():
    print k, ":", v
except InvalidTagError, message:
  print "Invalid ID3 tag:", message
吖咩 2024-07-11 04:06:36

在尝试了此处推荐的 eyeD3、pytaglib 和 ID3 模块的简单 pip install 路线后,我发现第四个选项是唯一可行的。 其余的都存在导入错误,缺少 C++ 中的依赖项或某些神奇的东西或 pip 错过的其他库。 因此,请使用这个来基本阅读 ID3 标签(所有版本):

https://pypi .python.org/pypi/tinytag/0.18.0

from tinytag import TinyTag
tag = TinyTag.get('/some/music.mp3')

您可以使用 TinyTag 获得的可能属性列表:

tag.album         # album as string
tag.albumartist   # album artist as string
tag.artist        # artist name as string
tag.audio_offset  # number of bytes before audio data begins
tag.bitrate       # bitrate in kBits/s
tag.disc          # disc number
tag.disc_total    # the total number of discs
tag.duration      # duration of the song in seconds
tag.filesize      # file size in bytes
tag.genre         # genre as string
tag.samplerate    # samples per second
tag.title         # title of the song
tag.track         # track number as string
tag.track_total   # total number of tracks as string
tag.year          # year or data as string

正如所宣传的那样,它很小且独立。

After trying the simple pip install route for eyeD3, pytaglib, and ID3 modules recommended here, I found this fourth option was the only one to work. The rest had import errors with missing dependencies in C++ or something magic or some other library that pip missed. So go with this one for basic reading of ID3 tags (all versions):

https://pypi.python.org/pypi/tinytag/0.18.0

from tinytag import TinyTag
tag = TinyTag.get('/some/music.mp3')

List of possible attributes you can get with TinyTag:

tag.album         # album as string
tag.albumartist   # album artist as string
tag.artist        # artist name as string
tag.audio_offset  # number of bytes before audio data begins
tag.bitrate       # bitrate in kBits/s
tag.disc          # disc number
tag.disc_total    # the total number of discs
tag.duration      # duration of the song in seconds
tag.filesize      # file size in bytes
tag.genre         # genre as string
tag.samplerate    # samples per second
tag.title         # title of the song
tag.track         # track number as string
tag.track_total   # total number of tracks as string
tag.year          # year or data as string

It was tiny and self-contained, as advertised.

我恋#小黄人 2024-07-11 04:06:36

看看这个:

https://github.com/Ciantic/songdetails

使用示例:

>>> import songdetails
>>> song = songdetails.scan("data/song.mp3")
>>> print song.duration
0:03:12

保存更改:

>>> import songdetails
>>> song = songdetails.scan("data/commit.mp3")
>>> song.artist = "Great artist"
>>> song.save()

check this one out:

https://github.com/Ciantic/songdetails

Usage example:

>>> import songdetails
>>> song = songdetails.scan("data/song.mp3")
>>> print song.duration
0:03:12

Saving changes:

>>> import songdetails
>>> song = songdetails.scan("data/commit.mp3")
>>> song.artist = "Great artist"
>>> song.save()
欢你一世 2024-07-11 04:06:36

只是向你们提供更多信息:

请查看 PythonInMusic 页面中的“MP3 内容和元数据编辑器”部分

Just additional information to you guys:

take a look at the section "MP3 stuff and Metadata editors" in the page of PythonInMusic.

月朦胧 2024-07-11 04:06:36

我使用 tinytag 1.3.1 因为

  1. 它受到积极支持:
1.3.0 (2020-03-09):
added option to ignore encoding errors ignore_errors #73
Improved text decoding for many malformed files
  1. 它支持主要格式:
MP3 (ID3 v1, v1.1, v2.2, v2.3+)
Wave/RIFF
OGG
OPUS
FLAC
WMA
MP4/M4A/M4B
  1. 代码可用于只需几分钟的开发时间。
from tinytag import TinyTag

fileNameL ='''0bd1ab5f-e42c-4e48-a9e6-b485664594c1.mp3
0ea292c0-2c4b-42d4-a059-98192ac8f55c.mp3
1c49f6b7-6f94-47e1-a0ea-dd0265eb516c.mp3
5c706f3c-eea4-4882-887a-4ff71326d284.mp3
'''.split()

for fn in fileNameL:
    fpath = './data/'+fn
    tag = TinyTag.get(fpath)
    print()
    print('"artist": "%s",' % tag.artist)
    print('"album": "%s",' % tag.album)
    print('"title": "%s",' % tag.title)
    print('"duration(secs)": "%s",' % tag.duration)

  • 结果
JoeTagPj>python joeTagTest.py

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "17. Thomas Middleditch and Ben Schwartz",
"duration(secs)": "3565.1829583532785",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "Are you ready to make friends?",
"duration(secs)": "417.71840447045264",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "Introducing Conan’s new podcast",
"duration(secs)": "327.22187551899646",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "19. Ray Romano",
"duration(secs)": "3484.1986772305863",

C:\1d\PodcastPjs\JoeTagPj>

I used tinytag 1.3.1 because

  1. It is actively supported:
1.3.0 (2020-03-09):
added option to ignore encoding errors ignore_errors #73
Improved text decoding for many malformed files
  1. It supports the major formats:
MP3 (ID3 v1, v1.1, v2.2, v2.3+)
Wave/RIFF
OGG
OPUS
FLAC
WMA
MP4/M4A/M4B
  1. The code WORKED in just a few minutes of development.
from tinytag import TinyTag

fileNameL ='''0bd1ab5f-e42c-4e48-a9e6-b485664594c1.mp3
0ea292c0-2c4b-42d4-a059-98192ac8f55c.mp3
1c49f6b7-6f94-47e1-a0ea-dd0265eb516c.mp3
5c706f3c-eea4-4882-887a-4ff71326d284.mp3
'''.split()

for fn in fileNameL:
    fpath = './data/'+fn
    tag = TinyTag.get(fpath)
    print()
    print('"artist": "%s",' % tag.artist)
    print('"album": "%s",' % tag.album)
    print('"title": "%s",' % tag.title)
    print('"duration(secs)": "%s",' % tag.duration)

  • RESULT
JoeTagPj>python joeTagTest.py

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "17. Thomas Middleditch and Ben Schwartz",
"duration(secs)": "3565.1829583532785",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "Are you ready to make friends?",
"duration(secs)": "417.71840447045264",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "Introducing Conan’s new podcast",
"duration(secs)": "327.22187551899646",

"artist": "Conan O’Brien Needs A Friend",
"album": "Conan O’Brien Needs A Friend",
"title": "19. Ray Romano",
"duration(secs)": "3484.1986772305863",

C:\1d\PodcastPjs\JoeTagPj>
风柔一江水 2024-07-11 04:06:36

最简单的方法是 songdetails..

用于读取数据

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    print song.artist

,类似地用于编辑

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    song.artist = u"The Great Blah"
    song.save()

不要忘记添加 u 在名字之前,直到你懂中文。

批量读取和编辑。

你可以使用 python glob 模块ex

import glob
songs = glob.glob('*')   # script should be in directory of songs.
for song in songs:
    # do the above work.

easiest method is songdetails..

for read data

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    print song.artist

similarly for edit

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    song.artist = u"The Great Blah"
    song.save()

Don't forget to add u before name until you know chinese language.

u can read and edit in bulk using python glob module

ex.

import glob
songs = glob.glob('*')   # script should be in directory of songs.
for song in songs:
    # do the above work.
夜还是长夜 2024-07-11 04:06:36

我查看了上面的答案,发现它们不适合我的项目,因为 GPL 的许可问题。

我发现了这一点:PyID3Lib,而特定的python绑定发布日期是旧的,它使用 ID3Lib,它本身是最新的。

值得注意的是,两者都是LGPL,并且都可以使用。

I looked the above answers and found out that they are not good for my project because of licensing problems with GPL.

And I found out this: PyID3Lib, while that particular python binding release date is old, it uses the ID3Lib, which itself is up to date.

Notable to mention is that both are LGPL, and are good to go.

苍风燃霜 2024-07-11 04:06:36

《Dive Into Python》一书中的一个简单示例对我来说效果很好,这个 是下载链接,示例是fileinfo.py。 不知道它是否是最好的,但它可以完成基本的工作。

整本书可在此处在线获取。

A simple example from the book Dive Into Python works ok for me, this is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job.

The entire book is available online here.

滥情稳全场 2024-07-11 04:06:36

使用 eyed3 的第一个答案已过时,因此这里是它的更新版本。

从 mp3 文件中读取标签:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 print(audiofile.tag.artist)
 print(audiofile.tag.album)
 print(audiofile.tag.album_artist)
 print(audiofile.tag.title)
 print(audiofile.tag.track_num)

网站上修改标签的示例:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 audiofile.tag.artist = u"Integrity"
 audiofile.tag.album = u"Humanity Is The Devil"
 audiofile.tag.album_artist = u"Integrity"
 audiofile.tag.title = u"Hollow"
 audiofile.tag.track_num = 2

我第一次尝试使用 eyesed3 时遇到的问题与 libmagic 的导入错误有关,即使它已安装。 要修复此问题,请从此处安装 magic-bin whl

The first answer that uses eyed3 is outdated so here is an updated version of it.

Reading tags from an mp3 file:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 print(audiofile.tag.artist)
 print(audiofile.tag.album)
 print(audiofile.tag.album_artist)
 print(audiofile.tag.title)
 print(audiofile.tag.track_num)

An example from the website to modify tags:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 audiofile.tag.artist = u"Integrity"
 audiofile.tag.album = u"Humanity Is The Devil"
 audiofile.tag.album_artist = u"Integrity"
 audiofile.tag.title = u"Hollow"
 audiofile.tag.track_num = 2

An issue I encountered while trying to use eyed3 for the first time had to do with an import error of libmagic even though it was installed. To fix this install the magic-bin whl from here

亣腦蒛氧 2024-07-11 04:06:36

我建议mp3-tagger。 最好的事情是它是在MIT 许可证下分发的,并且支持所有必需的属性。

- artist;
- album;
- song;
- track;
- comment;
- year;
- genre;
- band;
- composer;
- copyright;
- url;
- publisher.

示例:

from mp3_tagger import MP3File

# Create MP3File instance.
mp3 = MP3File('File_Name.mp3')

# Get all tags.
tags = mp3.get_tags()
print(tags)

支持mp3文件的set、get、update、delete属性。

I would suggest mp3-tagger. Best thing about this is it is distributed under MIT License and supports all the required attributes.

- artist;
- album;
- song;
- track;
- comment;
- year;
- genre;
- band;
- composer;
- copyright;
- url;
- publisher.

Example:

from mp3_tagger import MP3File

# Create MP3File instance.
mp3 = MP3File('File_Name.mp3')

# Get all tags.
tags = mp3.get_tags()
print(tags)

It supports set, get, update and delete attributes of mp3 files.

心安伴我暖 2024-07-11 04:06:36

使用 https://github.com/nicfit/eyeD3

import eyed3
import os

for root,  dirs, files in os.walk(folderp):
    for file in files:
        try:
            if file.find(".mp3") < 0:
                continue
            path = os.path.abspath(os.path.join(root , file))
            t = eyed3.load(path)
            print(t.tag.title , t.tag.artist)
            #print(t.getArtist())
        except Exception as e:
            print(e)
            continue

using https://github.com/nicfit/eyeD3

import eyed3
import os

for root,  dirs, files in os.walk(folderp):
    for file in files:
        try:
            if file.find(".mp3") < 0:
                continue
            path = os.path.abspath(os.path.join(root , file))
            t = eyed3.load(path)
            print(t.tag.title , t.tag.artist)
            #print(t.getArtist())
        except Exception as e:
            print(e)
            continue
痴情换悲伤 2024-07-11 04:06:36

这可能取决于除了读取元数据之外您还想做什么。 如果您只需要比特率/名称等,而没有其他任何东西,那么轻量级的东西可能是最好的。

如果您要处理过去的 mp3,PyMedia 可能适合。

有很多,无论您得到什么,请确保并在大量示例媒体上进行测试。 特别是 ID3 标签有几个不同的版本,因此请确保它不过时。

就我个人而言,我很幸运地使用了这个小型 MP3Info 类。 虽然它已经很旧了。

http://www.omniscia.org/~vivake/python/MP3Info.py< /a>

It can depend on exactly what you want to do in addition to reading the metadata. If it is just simply the bitrate / name etc. that you need, and nothing else, something lightweight is probably best.

If you're manipulating the mp3 past that PyMedia may be suitable.

There are quite a few, whatever you do get, make sure and test it out on plenty of sample media. There are a few different versions of ID3 tags in particular, so make sure it's not too out of date.

Personally I've used this small MP3Info class with luck. It is quite old though.

http://www.omniscia.org/~vivake/python/MP3Info.py

小帐篷 2024-07-11 04:06:36

经过一些初步研究,我认为歌曲详细信息可能适合我的用例,但它不处理 .m4b 文件。 诱变剂确实如此。 请注意,虽然有些人(合理地)对 Mutagen 的格式本机键的表面提出了问题,但不同格式的键有所不同(mp3 为 TIT2,ogg 为 title,mp4 为 \xa9nam,WMA 为 Title 等), mutagen.File( )有一个(新?)easy=True 参数,它提供 EasyMP3/EasyID3 标签,这些标签具有一致但有限的​​键集。 到目前为止,我只进行了有限的测试,但是当使用 easy=True 时,.mb4 和 .mp3 文件的通用键(例如专辑、艺术家、专辑艺术家、流派、曲目编号、光盘编号等)都存在并且相同,从而使其成为可能对于我的目的来说非常方便。

After some initial research I thought songdetails might fit my use case, but it doesn't handle .m4b files. Mutagen does. Note that while some have (reasonably) taken issue with Mutagen's surfacing of format-native keys, that vary from format to format (TIT2 for mp3, title for ogg, \xa9nam for mp4, Title for WMA etc.), mutagen.File() has a (new?) easy=True parameter that provides EasyMP3/EasyID3 tags, which have a consistent, albeit limited, set of keys. I've only done limited testing so far, but the common keys, like album, artist, albumartist, genre, tracknumber, discnumber, etc. are all present and identical for .mb4 and .mp3 files when using easy=True, making it very convenient for my purposes.

尐籹人 2024-07-11 04:06:35

前几天我使用了 eyeD3 并取得了很大的成功。 我发现它可以将艺术品添加到 ID3 标签,而我查看的其他模块却不能。 您必须使用 pip 安装或下载 tar 并从源文件夹执行 python setup.py install 。

网站上的相关示例如下。

读取包含 v1 或 v2 标签信息的 mp3 文件的内容:

 import eyeD3
 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 print tag.getArtist()
 print tag.getAlbum()
 print tag.getTitle()

读取 mp3 文件(曲目长度、比特率等)并访问其标签:

if eyeD3.isMp3File(f):
     audioFile = eyeD3.Mp3AudioFile(f)
     tag = audioFile.getTag()

可以选择特定标签版本:

 tag.link("/some/file.mp3", eyeD3.ID3_V2)
 tag.link("/some/file.mp3", eyeD3.ID3_V1)
 tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION)  # The default.

或者您可以迭代原始帧:

 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 for frame in tag.frames:
    print frame

一次标签链接到文件,可以对其进行修改和保存:

 tag.setArtist(u"Cro-Mags")
 tag.setAlbum(u"Age of Quarrel")
 tag.update()

如果链接的标签是 v2 并且您想将其另存为 v1:

 tag.update(eyeD3.ID3_V1_1)

读入标签并将其从文件中删除:

 tag.link("/some/file.mp3")
 tag.remove()
 tag.update()

添加新标签:

 tag = eyeD3.Tag()
 tag.link('/some/file.mp3')    # no tag in this file, link returned False
 tag.header.setVersion(eyeD3.ID3_V2_3)
 tag.setArtist('Fugazi')
 tag.update()

I used eyeD3 the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute python setup.py install from the source folder.

Relevant examples from the website are below.

Reading the contents of an mp3 file containing either v1 or v2 tag info:

 import eyeD3
 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 print tag.getArtist()
 print tag.getAlbum()
 print tag.getTitle()

Read an mp3 file (track length, bitrate, etc.) and access it's tag:

if eyeD3.isMp3File(f):
     audioFile = eyeD3.Mp3AudioFile(f)
     tag = audioFile.getTag()

Specific tag versions can be selected:

 tag.link("/some/file.mp3", eyeD3.ID3_V2)
 tag.link("/some/file.mp3", eyeD3.ID3_V1)
 tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION)  # The default.

Or you can iterate over the raw frames:

 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 for frame in tag.frames:
    print frame

Once a tag is linked to a file it can be modified and saved:

 tag.setArtist(u"Cro-Mags")
 tag.setAlbum(u"Age of Quarrel")
 tag.update()

If the tag linked in was v2 and you'd like to save it as v1:

 tag.update(eyeD3.ID3_V1_1)

Read in a tag and remove it from the file:

 tag.link("/some/file.mp3")
 tag.remove()
 tag.update()

Add a new tag:

 tag = eyeD3.Tag()
 tag.link('/some/file.mp3')    # no tag in this file, link returned False
 tag.header.setVersion(eyeD3.ID3_V2_3)
 tag.setArtist('Fugazi')
 tag.update()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文