mail@pastecode.io avatarunknown
a month ago
2.1 kB
import mutagen
from mutagen.id3 import ID3, TIT2, TPE1, TALB, APIC
import requests
from bs4 import BeautifulSoup

# Function to scrape Wikipedia for metadata
def scrape_wikipedia(artist, song_title):
    # Create a Wikipedia search query URL
    search_query = f"https://en.wikipedia.org/wiki/{artist}_{song_title}"

        # Send an HTTP GET request to the Wikipedia page
        response = requests.get(search_query)

        # Check if the request was successful
        if response.status_code == 200:
            # Parse the HTML content of the page using BeautifulSoup
            soup = BeautifulSoup(response.text, 'html.parser')

            # Extract relevant information, such as album and release year
            album = soup.find("div", class_="infobox-data").text.strip()
            release_year = soup.find("span", class_="bday").text.strip()[:4]

            return album, release_year

    except Exception as e:
        print(f"Error scraping Wikipedia: {str(e)}")

    return None, None

# Function to add metadata to an MP3 file
def add_metadata_to_mp3(mp3_file, artist, song_title):
    audio = ID3(mp3_file)

    # Scrape Wikipedia for album and release year
    album, release_year = scrape_wikipedia(artist, song_title)

    if album and release_year:
        # Add metadata tags to the MP3 file
        audio["TIT2"] = TIT2(encoding=3, text=song_title)
        audio["TPE1"] = TPE1(encoding=3, text=artist)
        audio["TALB"] = TALB(encoding=3, text=album)
        audio["TDRC"] = TDRC(encoding=3, text=release_year)

        # Save the changes to the MP3 file

        print("Metadata added successfully.")
        print("Metadata retrieval from Wikipedia failed.")

# Example usage
if __name__ == "__main__":
    mp3_file = "your_song.mp3"  # Replace with the path to your MP3 file
    artist = "Your_Artist"      # Replace with the artist's name
    song_title = "Your_Song"    # Replace with the song title

    add_metadata_to_mp3(mp3_file, artist, song_title)