Convert mp4 to mp3 with Python

How to convert mp4, wav, mpeg4 or mp4a to mp3 with Python and moviepy?

Install moviepy library:

pip install moviepy

Python script to convert mp4 to mp3:

from moviepy.editor import *

# Load the mp4 file
video = VideoFileClip("C:/my-dev/use.mp4")

# Extract audio from video
video.audio.write_audiofile("C:/my-dev/use.mp3")

Python function to convert video to mp3:

from moviepy.editor import *

def mp4_to_mp3(mp4, mp3):
file_to_convert = VideoFileClip(mp4)
file_to_convert.audio.write_audiofile(mp3)
file_to_convert.close()

# path to mp4 file
mp4_file_path = "C:/my-dev/use.mp4"
#path for mp3 file to be saved
mp3_file_path = "C:/my-dev/use.mp4"
# run function
mp4_to_mp3(mp4_file_path, mp3_file_path)

If you have the KeyError: 'video_fps', ensure that you are not using any video which does not contain any visual content.

How this script works?

  1. Importing the module:

    from moviepy.editor import *

    This line imports all the classes and functions from the moviepy.editor module. The asterisk * indicates that everything from the module is imported, although it's generally recommended to import only what you need to keep the namespace clean.

  2. Loading the video file:

    video = VideoFileClip("C:/my-dev/use.mp4")

    Here, the VideoFileClip class is used to create an object representing the video file located at the given path "C:/my-dev/use.mp4". The video variable now holds a clip object that can be manipulated using moviepy functions.

  3. Extracting audio from the video:

    video.audio.write_audiofile("C:/my-dev/use.mp3")

    This line accesses the audio attribute of the video object, which contains the audio clip of the video. The write_audiofile method is then called on this audio clip to write it to a file. The method takes a file path as an argument, and in this case, it will write the extracted audio to "C:/my-dev/use.mp3" in MP3 format.

Python function to convert video to mp3:
Python GUI drag and drop to convert mp4 to mp3

How this script works:

  1. The script utilizes a simple drag and drop feature with tkinter's dnd module (if it's available in your version of tkinter).
  2. The MP4 file's path will be shown on the GUI after dragging and dropping.
  3. The user can then select the output folder by clicking on the "Select Output Folder" button.
    Finally, clicking on "Convert to MP3" will do the conversion.
from tkinterdnd2 import DND_FILES, Tk
from tkinter import Button, Label, Frame, filedialog, messagebox
from moviepy.editor import *


class MP4toMP3Converter:
def __init__(self, root):
self.root = root
self.root.title("MP4 to MP3 Converter")
self.root.geometry("400x200")

# Widgets
self.instructions = Label(root, text="Drag & Drop your MP4 file here:")
self.instructions.pack(pady=20)

self.file_path = ""
self.output_folder = ""

self.drop_frame = Frame(root, bg="lightgrey", width=300, height=100)
self.drop_frame.pack(pady=20)
self.drop_frame.drop_target_register(DND_FILES)
self.drop_frame.dnd_bind('<<Drop>>', self.drop)

self.output_button = Button(root, text="Select Output Folder", command=self.select_output_folder)
self.output_button.pack(pady=20)

self.convert_button = Button(root, text="Convert to MP3", command=self.convert)
self.convert_button.pack(pady=20)

def drop(self, event):
self.file_path = event.data
self.instructions.config(text=self.file_path)
return None

# def drop(self, event):
# self.file_path = self.root.drop_file
# self.instructions.config(text=self.file_path)
# return None

def select_output_folder(self):
self.output_folder = filedialog.askdirectory()
return None

def convert(self):
try:
if not self.file_path:
messagebox.showerror("Error", "No MP4 file selected!")
return

if not self.output_folder:
messagebox.showerror("Error", "No output folder selected!")
return

clip = AudioFileClip(self.file_path)
clip.export(f"{self.output_folder}/output.mp3", format="mp3")
clip.close()
messagebox.showinfo("Success", "File converted successfully!")

except Exception as e:
messagebox.showerror("Error", f"Error occurred: {str(e)}")
return


if __name__ == "__main__":
root = Tk()
app = MP4toMP3Converter(root)
root.mainloop()

Published