Home > Back-end >  Need to use python to convert media files to mp3 files
Need to use python to convert media files to mp3 files

Time:06-25

import moviepy.editor as m
import os
for i in os.listdir():
    if i == ".mpeg": #How do I make that work(I know it can't, I just have it there to explain what I need)
        video = m.VideoFileClip(i)
        video.audio.write_audiofile(i)

Need it to sort through files, find the media ones, and change them to .mp3

CodePudding user response:

Here's how I would change your code. Extract the filename and extension, use the extension to filter files and use the filename to create a new filename with the .mp3 extension. This makes sure you don't overwrite your source video file with audio.

import moviepy.editor as m
import os
for file_path in os.listdir():
    filename, file_extension = os.path.splitext(file_path)
    if file_extension == ".mpeg":
        video = m.VideoFileClip(file_path)
        audio_file_path = filename   ".mp3"
        video.audio.write_audiofile(audio_file_path)
  • Related