0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

mp3 m4a アートワーク カバー ジャケット 画像

Posted at
import os

from mutagen.id3 import ID3
from mutagen.id3._frames import APIC  # type: ignore[reportPrivateImportUsage]
from mutagen.id3._util import ID3NoHeaderError  # type: ignore[reportPrivateImportUsage]
from mutagen.mp4 import MP4, MP4Cover


class EmbedCover:
    def embed(self, audio_path: str, image_path: str):
        ext = os.path.splitext(audio_path)[1]
        if ext == ".mp3":
            self.embed_cover_mp3(audio_path, image_path)
        elif ext == ".m4a":
            self.embed_cover_m4a(audio_path, image_path)

    def embed_cover_mp3(self, audio_path: str, image_path: str) -> None:
        try:
            tags = ID3(audio_path)
        except ID3NoHeaderError:
            tags = ID3()
            tags.save(audio_path)
            tags = ID3(audio_path)

        with open(image_path, "rb") as f:
            img = f.read()

        # MIME は JPEG か PNG に合わせる
        mime = "image/jpeg" if image_path.lower().endswith(".jpg") else "image/png"

        # 既存の画像タグを削除してから追加(重複防止)
        tags.delall("APIC")
        tags.add(
            APIC(
                encoding=3,  # UTF-8
                mime=mime,
                type=3,  # Cover (front)
                desc="Cover",
                data=img,
            )
        )
        tags.save(v2_version=3)  # ID3v2.3 で保存(互換性高い)

    def embed_cover_m4a(self, audio_path, image_path):
        audio = MP4(audio_path)
        with open(image_path, "rb") as f:
            img = f.read()
        # JPEGならFORMAT_JPEG、PNGならFORMAT_PNG
        audio["covr"] = [MP4Cover(img, imageformat=MP4Cover.FORMAT_JPEG)]
        audio.save()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?