Python – Adding image to mp3 files in folder

Question:

I have a folder with 10 ".mp3" songs, I want to add an image to those songs and render all files in mp4 format,
but I am getting an error : AttributeError: ‘WindowsPath’ object has no attribute ‘endswith’

Code:

from moviepy.editor import *
from pathlib import Path

music_folder = Path(r'C:UsersPycharmProjectsAudio')
Image = ImageClip(r'C:UsersPycharmProjectsImageimage.jpg')

for i in music_folder.glob("*.mp3"):
    audio_clip = AudioFileClip(i)

    clip = Image.set_duration(audio_clip.duration)
    clip = clip.set_audio(audio_clip)

    clip.write_videofile('Final.mp4', fps=4)

Error:

Traceback (most recent call last):
  File "C:UsersPycharmProjectsmain.py", line 9, in <module>
    audio_clip = AudioFileClip(i)
  File "C:UsersPycharmProjectsvenvlibsite-packagesmoviepyaudioioAudioFileClip.py", line 70, in __init__
    self.reader = FFMPEG_AudioReader(filename, fps=fps, nbytes=nbytes,
  File "C:UsersPycharmProjectsvenvlibsite-packagesmoviepyaudioioreaders.py", line 51, in __init__
    infos = ffmpeg_parse_infos(filename)
  File "C:UsersPycharmProjectsvenvlibsite-packagesmoviepyvideoioffmpeg_reader.py", line 244, in ffmpeg_parse_infos
    is_GIF = filename.endswith('.gif')
AttributeError: 'WindowsPath' object has no attribute 'endswith'

`

Asked By: Akshay Lokhande

||

Answers:

The AudioFileClip class apparently can’t accept a pathlib.Path argument; you’ll need to convert it to a string.

AudioFileClip(str(i))

or convert the code to process strings instead of Path objects. (Basically, import glob and do for i in glob.glob(os.path.join(r'C:UsersPycharmProjectsAudio', "*.mp3"))

When pathlib was new, this was a quite common problem, so you can probably find duplicates of earlier questions about the same symptom. These days, you’d expect most libraries which accept files to also accept Path objects as arguments.

Answered By: tripleee
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.