Home > Back-end >  Python - Adding image to mp3 files in folder
Python - Adding image to mp3 files in folder

Time:10-12

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:\Users\PycharmProjects\Audio')
Image = ImageClip(r'C:\Users\PycharmProjects\Image\image.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:\Users\PycharmProjects\main.py", line 9, in <module>
    audio_clip = AudioFileClip(i)
  File "C:\Users\PycharmProjects\venv\lib\site-packages\moviepy\audio\io\AudioFileClip.py", line 70, in __init__
    self.reader = FFMPEG_AudioReader(filename, fps=fps, nbytes=nbytes,
  File "C:\Users\PycharmProjects\venv\lib\site-packages\moviepy\audio\io\readers.py", line 51, in __init__
    infos = ffmpeg_parse_infos(filename)
  File "C:\Users\PycharmProjects\venv\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 244, in ffmpeg_parse_infos
    is_GIF = filename.endswith('.gif')
AttributeError: 'WindowsPath' object has no attribute 'endswith'

`

CodePudding user response:

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:\Users\PycharmProjects\Audio', "*.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.

  • Related