pythonpytubemutagen

Unable to Play MP3 Song After Adding Artwork Using Mutagen


I am utilizing the pytube library to download audio content from YouTube successfully. However, when attempting to add a thumbnail to the downloaded MP3 file using the mutagen library, the file becomes unplayable. The audio portion remains functional until the thumbnail is added, at which point the file appears to be corrupted or inaccessible. I also tried with eyed3 but the same thing.

Code:

from os import rename
from os.path import exists, expanduser, splitext
from pytube import YouTube, Search
from requests import get
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC

yt = YouTube(link)
print(f'Downloading...')
audio_stream = yt.streams.filter(only_audio=True).first()
download_file = audio_stream.download(output_path=download_path)
base, _ = splitext(download_file)
out_file = base + '.mp3'
rename(download_file, out_file)

thumbnail = get(yt.thumbnail_url).content
audio = MP3(out_file, ID3=ID3)

if audio.tags is None:
    audio.add_tags()
    
audio.tags.add(
    APIC(
        encoding=3,
        mime='image/jpeg',
        type=3,
        desc=u'Cover',
        data=thumbnail
    )
)
audio.save()

Solution

  • You need to convert file to mp3 format, not just rename file extension. You can use pydub lib for converting. Also make sure you have ffmpeg installed.

    import os
    import pydub
    import pytube
    import requests
    from mutagen.mp3 import MP3
    from mutagen.id3 import ID3, APIC
    
    yt = pytube.YouTube(link)
    download_file = yt.streams.filter(only_audio=True).first().download(output_path=download_path)
    out_file = os.path.splitext(download_file)[0] + '.mp3'
    pydub.AudioSegment.from_file(download_file).export(out_file, format='mp3')
    audio = MP3(out_file, ID3=ID3)
    if not audio.tags:
        audio.add_tags()
    audio.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=requests.get(yt.thumbnail_url).content))
    audio.save()
    os.remove(download_file)