gpt4 book ai didi

python - 在 Python 3 中使用 Mutagen 将专辑封面嵌入到 mp3

转载 作者:太空宇宙 更新时间:2023-11-03 15:57:18 25 4
gpt4 key购买 nike

ID3 .这是 Python 3 API,我不确定如何嵌入图像,到目前为止我在更改标签的地方有这个,

def addMetaData(url, title, artist, album, track):

response = requests.get(url, stream=True)
with open('img.jpg', 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response

audio = MP3(filename=title+".mp3", ID3 = EasyID3)
audio['artist'] = artist
audio['title'] = title
audio['tracknumber'] = track
audio['album'] = album

audio.save()

最佳答案

我不认为可以使用 EasyID3 嵌入专辑封面,但可以使用 ID3

您可以使用 ID3 嵌入专辑封面,如下所示:

from mutagen.id3 import ID3, APIC

audio = ID3('music_file.mp3')

with open('img.jpg', 'rb') as albumart:
audio['APIC'] = APIC(
encoding=3,
mime='image/jpeg',
type=3, desc=u'Cover',
data=albumart.read()
)

audio.save()

如果性能不是您的主要关注点,您可以使用 EasyID3 保存文本元数据,然后使用 ID3 再次加载音乐文件以嵌入专辑封面。否则,您可以完全使用 ID3

因此,第一种情况下的代码将是:

import requests
import shutil

# you can directly import EasyID3 and ID3
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3, APIC

def addMetaData(url, title, artist, album, track):

response = requests.get(url, stream=True)
with open('img.jpg', 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response

audio = EasyID3('music_file.mp3')
audio['artist'] = artist
audio['title'] = title
audio['tracknumber'] = track
audio['album'] = album
audio.save()

audio = ID3('music_file.mp3')
with open('img.jpg', 'rb') as albumart:
audio['APIC'] = APIC(
encoding=3,
mime='image/jpeg',
type=3, desc=u'Cover',
data=albumart.read()
)
audio.save()

第二种情况:

import requests
import shutil

from mutagen.id3 import ID3, TPE1, TIT2, TRCK, TALB, APIC

def addMetaData(url, title, artist, album, track):

response = requests.get(url, stream=True)
with open('img.jpg', 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response

audio = ID3('music_file.mp3')
audio['TPE1'] = TPE1(encoding=3, text=artist)
audio['TIT2'] = TALB(encoding=3, text=title)
audio['TRCK'] = TRCK(encoding=3, text=track)
audio['TALB'] = TALB(encoding=3, text=album)

with open('img.jpg', 'rb') as albumart:
audio['APIC'] = APIC(
encoding=3,
mime='image/jpeg',
type=3, desc=u'Cover',
data=albumart.read()
)
audio.save()

注意:您也可以使用 urllib2 直接嵌入专辑封面,而无需先将其保存在磁盘上。示例:

import urllib2
from mutagen.id3 import ID3, APIC

audio = ID3('music_file.mp3')
albumart = urllib2.urlopen(url)

audio['APIC'] = APIC(
encoding=3,
mime='image/jpeg',
type=3,
desc=u'Cover',
data=albumart.read()
)

albumart.close()
audio.save()

关于python - 在 Python 3 中使用 Mutagen 将专辑封面嵌入到 mp3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42473832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com