萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 讀取 MP3 ID3v1 標籤:手動解析最後 128 位元組

ID3v1 標籤格式

ID3v1 位於 MP3 檔案末尾固定 128 位元組:

欄位位移長度
TAG 標識03 bytes ("TAG")
標題330 bytes
歌手3330 bytes
專輯6330 bytes
年份934 bytes
備註9728 bytes
流派1251 byte

純 Python 解析函式

def get_id3v1(filename):
    with open(filename, 'rb') as f:
        f.seek(-128, 2)  # 從檔尾倒數 128 bytes
        tag = f.read(3)
        if tag != b'TAG':
            return None
        title = f.read(30).rstrip(b'\x00').decode('latin-1', errors='ignore')
        artist = f.read(30).rstrip(b'\x00').decode('latin-1', errors='ignore')
        album = f.read(30).rstrip(b'\x00').decode('latin-1', errors='ignore')
        year = f.read(4).rstrip(b'\x00').decode('latin-1', errors='ignore')
        comment = f.read(28).rstrip(b'\x00').decode('latin-1', errors='ignore')
        # genre byte 略
    return {'title': title, 'artist': artist, 'album': album, 'year': year, 'comment': comment}

使用範例

info = get_id3v1('song.mp3')
if info:
    print(f"Title: {info['title']}")
    print(f"Artist: {info['artist']}")
else:
    print("無 ID3v1 標籤")

注意事項

  • 僅適用 ID3v1 (舊版);現代多用 ID3v2 (位於檔頭、長度可變、支援 Unicode、封面圖)
  • 編碼通常為 ISO-8859-1 (latin-1),中文常存為 GBK/Big5,需嘗試多種解碼
  • 建議改用 mutagen 或 eyed3 同時支援 v1/v2
copyright © 萬盛學電腦網 all rights reserved