[Python] mp3 to base64 in python

Discussão em 'Python' iniciado por Stack, Janeiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I have this python code:

    def download_song_as_base64(song_name):
    try:
    # Create a temporary directory for the downloaded and converted files
    temp_dir = "./temp"
    os.makedirs(temp_dir, exist_ok=True)

    # Define file paths
    output_path = os.path.join(temp_dir, "%(title)s.%(ext)s")
    mp3_file = os.path.join(temp_dir, "song.mp3")

    # Download the video from YouTube
    ydl_opts = {
    'format': 'bestaudio/best',
    'outtmpl': output_path,
    'postprocessors': [{
    'key': 'FFmpegExtractAudio',
    'preferredcodec': 'mp3',
    'preferredquality': '192',
    }],
    }

    with YoutubeDL(ydl_opts) as ydl:
    info = ydl.extract_info(f"ytsearch:{song_name}", download=True)

    # Get the downloaded MP3 file name
    downloaded_file = ydl.prepare_filename(info['entries'][0]).replace(".webm", ".mp3").replace(".m4a", ".mp3")
    if not os.path.isfile(downloaded_file):
    raise FileNotFoundError(f"The file {downloaded_file} was not found.")
    # Encode the MP3 file in Base64
    with open(downloaded_file, 'rb') as audio_file:
    audio_data = audio_file.read()
    base64_audio = "data:audio/mpeg;base64," + base64.b64encode(audio_data).decode('utf-8')
    print(base64_audio)

    # Clean up temporary files
    for file in os.listdir(temp_dir):
    os.remove(os.path.join(temp_dir, file))
    os.rmdir(temp_dir)

    return base64_audio
    except Exception as e:
    print(f"Error downloading or converting song: {e}")
    return None


    But no matter what file I upload, the encoding to base64 comes out bad. I copy and paste it on the base64 to audio site, and it plays for less than a second of the song itself, and stops.

    Who knows where the fault is here? The mp3 file itself is correct and complete, I have already checked it. And it doesn't just happen in one file, it just creates the base64 encoding incorrectly.

    Where is the problem here?

    That a proper base64 will be created for my MP3 file.

    Continue reading...

Compartilhe esta Página