program tip

파이썬으로 mp3 메타 데이터 접근하기

radiobox 2020. 7. 27. 07:48
반응형

파이썬으로 mp3 메타 데이터 접근하기


파이썬에서 mp3 메타 데이터를 검색하는 가장 좋은 방법은 무엇입니까? 나는 몇 가지 프레임 워크를 보았지만 사용하기에 가장 적합한 것이 확실하지 않습니다 .... 어떤 아이디어?


나는 다른 날 eyeD3를 많은 성공으로 사용했습니다. 내가 본 다른 모듈이 할 수 없었던 ID3 태그에 아트웍을 추가 할 수 있다는 것을 알았습니다. 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()

이전에 미디어 파일의 태그를 편집하기 위해 mutagen사용했습니다 . mutagen의 좋은 점은 mp4, FLAC 등과 같은 다른 형식을 처리 할 수 ​​있다는 것입니다.이 API를 사용하여 많은 스크립트를 성공적으로 작성했습니다.


문제 eyed3NotImplementedError("Unable to write ID3 v2.2")일반적인 MP3 파일을 처리 한다는 것입니다 .

내 경험상 mutagen수업 EasyID3이 더 안정적으로 작동합니다. 예:

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 Tutorial 에서 찾을 수 있습니다 .


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

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

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.


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.


Just additional information to you guys:

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


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.

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.


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.


This toolkit may do what you need. I can't say if it's the "best", but really, if it does what you need, that's all that matters, right?

HTH


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


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


If you can use IronPython, there is TagLibSharp. It can be used from any .NET language.


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.

참고URL : https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python

반응형