MP3 file reader - Python Programming Exercise

In this exercise, you will develop a Python program to read the ID3 tags from an MP3 file. This exercise is perfect for practicing file handling, byte manipulation, and data extraction in Python. By implementing this program, you will gain hands-on experience in handling file operations, byte manipulation, and data extraction in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

MP3 File Reader

 Objective

Develop a Python program to read the ID3 tags from an MP3 file. The program should extract the ID3v1.1 tag, which is appended at the end of the file and is always 128 bytes in size.

The program must look for the "TAG" header to confirm the presence of an ID3v1.1 tag, then proceed to read the following:

- Title: 30 ASCII characters
- Artist: 30 ASCII characters
- Album: 30 ASCII characters
- Year: 4 characters
- Comment: 30 ASCII characters
- Genre: 1 byte (an integer representing a musical genre)

It should display this information and handle cases where no ID3 tag exists in the file. The program should use appropriate Python methods to handle binary data, ensuring correct interpretation of the genres and characters.

 Example Python Exercise

 Copy Python Code
# Python program to read ID3v1.1 tags from an MP3 file

def read_id3_tags(mp3_file):
    try:
        with open(mp3_file, "rb") as file:
            # Move the pointer to the last 128 bytes (ID3v1.1 tag is always at the end)
            file.seek(-128, 2)  # Seek 128 bytes from the end of the file
            
            # Read the last 128 bytes
            tag = file.read(128)
            
            # Check for the "TAG" header indicating an ID3v1.1 tag
            if tag[0:3].decode("ascii") == "TAG":
                # Extract the ID3v1.1 information
                title = tag[3:33].decode("ascii", errors="ignore").strip()
                artist = tag[33:63].decode("ascii", errors="ignore").strip()
                album = tag[63:93].decode("ascii", errors="ignore").strip()
                year = tag[93:97].decode("ascii", errors="ignore").strip()
                comment = tag[97:127].decode("ascii", errors="ignore").strip()
                genre = tag[127]  # Genre is a single byte (integer)

                # List of standard genre numbers (ID3v1.1 standard list)
                genres = [
                    "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge",
                    "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B",
                    "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", "Death Metal",
                    "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk",
                    "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip",
                    "Gospel", "Noise", "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative",
                    "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial",
                    "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta Rap",
                    "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave",
                    "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz",
                    "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk",
                    "Swing", "Fast-Fusion", "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock",
                    "Progressive Rock", "Psychedelic Rock", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad",
                    "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", "Acapella", "Euro-House", "Dance Hall"
                ]
                
                genre_name = genres[genre] if genre < len(genres) else "Unknown"
                
                # Print the extracted ID3v1.1 tag information
                print(f"Title: {title}")
                print(f"Artist: {artist}")
                print(f"Album: {album}")
                print(f"Year: {year}")
                print(f"Comment: {comment}")
                print(f"Genre: {genre_name}")
            else:
                print("No ID3v1.1 tag found in this file.")
    except FileNotFoundError:
        print(f"Error: The file '{mp3_file}' does not exist.")
    except Exception as e:
        print(f"Error: {str(e)}")

# Example usage
read_id3_tags("example.mp3")

 Output

Title: Sample Song
Artist: Sample Artist
Album: Sample Album
Year: 2024
Comment: Sample Comment
Genre: Rock

 Share this Python Exercise

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  File Divider

    In this exercise, you will develop a Python program to divide a file (of any type) into smaller segments of a specified size. This exercise is perfect for prac...

  •  BMP File Encryption

    In this exercise, you will develop a Python program to encrypt or decrypt a BMP image file by swapping the "BM" signature in the first two bytes with "MB" and vice ve...

  •  CSV Data Converter

    In this exercise, you will develop a Python program to read a CSV file containing comma-separated values. This exercise is perfect for practicing file handling...

  •  File content comparer

    In this exercise, you will develop a Python program to compare two files (of any type) and determine if they are identical (i.e., have the same content). This exer...

  •  Show BMP on console

    In this exercise, you will develop a Python program to decode and display a Netpbm image file. This exercise is perfect for practicing file handling, string ma...

  •  Extract Text Information from a Binary File

    In this exercise, you will develop a Python program to extract only the alphabetic characters contained in a binary file and dump them into a separate file. This e...