部分 MP3 內嵌大尺寸封面圖片 (ID3v2 標籤),導致檔案膨脹。移除 ID3v2 可大幅減小體積,適用於不支援 ID3v2 的老舊 MP3 播放器。
"ID3"標籤總大小 = 10 (標頭) + size。
import struct, os, shutil
def clear_mp3(src, dst):
with open(src, 'rb') as sf:
head = sf.read(3)
if head != b'ID3':
shutil.copyfile(src, dst)
return
sf.seek(3, 1) # 跳過版本標誌
size_bytes = sf.read(4)
# synchsafe 解碼
size = ((size_bytes[0] & 0x7f) << 21) | \
((size_bytes[1] & 0x7f) << 14) | \
((size_bytes[2] & 0x7f) << 7) | \
(size_bytes[3] & 0x7f)
tag_size = 10 + size
# 複製剩餘音訊資料
sf.seek(tag_size)
with open(dst, 'wb') as df:
while True:
chunk = sf.read(1024)
if not chunk: break
df.write(chunk)
.mp3python mp3_clear.py source_dir dest_dir
單檔縮減 400KB+ (封面圖),數十首歌可省出一首歌空間。
# mutagen 保留 ID3v2 但移除封面
from mutagen.id3 import ID3
tags = ID3('song.mp3')
del tags['APIC'] # 刪除封面
tags.save()
mutagen 更安全、支援 Unicode、可選擇性保留其他標籤。