In today’s digital age, extracting audio from video files has become a highly sought-after skill. Whether for professional use, educational purposes, or personal enjoyment, the ability to convert video into audio efficiently can significantly enhance how we interact with media.
As a follow-up to our previous article on building a YouTube Video Downloader with Tkinter. In today’s tutorial, we’re going to create a program that turns a video into an audio file using Python. This program will feature an interface that allows users to pick a video and choose where to save the audio file.
Let’s get started!
Table of Contents
- Necessary Libraries
- Imports
- Defining the Audio Extraction Function
- Defining Functions for Browsing Video and Audio Files
- Creating the Main Window
- Creating GUI Elements
- Main Program Loop
- Example
- Full Code
Necessary Libraries
For this code to function properly, make sure to install the tkinter and moviepy libraries by running these commands via the terminal or your command prompt:
$ pip install tk
$ pip install moviepy
Imports
As usual, we start by importing the libraries that we are going to use. First, we import tkinter
, which allows us to create a graphical user interface (GUI). From tkinter
, we import filedialog
, which helps in opening file dialogs for file selection. Lastly, we import moviepy.editor
, which is used for editing videos and audio files.
import tkinter as tk
from tkinter import filedialog
import moviepy.editor as mp
Defining the Audio Extraction Function
Next, we define a function that initiates when the user clicks on the “Convert to Audio” button. Once initiated, this function retrieves the paths for both the video and the desired audio output from the GUI entry fields. It then attempts to open the video file to extract its audio content and write it to a new file. If this operation succeeds, a success message is displayed in the status label to inform the user. Otherwise, an error message will appear if something goes wrong.
def extract_audio():
video_path = entry_video.get()
audio_path = entry_audio.get()
try:
clip = mp.VideoFileClip(video_path)
audio = clip.audio
# You can customize the audio processing here if needed
# For example, you can apply filters, adjust volume, etc.
audio.write_audiofile(audio_path, codec="pcm_s16le", bitrate="192k", logger=None)
status_label.config(text="Audio extraction complete.")
except Exception as e:
status_label.config(text=f"Error: {str(e)}")
Defining Functions for Browsing Video and Audio Files
Following that, we implement the browse_video
function that is designed to select a video file by opening a file dialog. Then update the corresponding entry field with the file’s path. Similarly, the browse_audio
function enables the user to select a location and name for the audio file. Once selected, it updates the entry field and displays the path.
def browse_video():
video_path = filedialog.askopenfilename(filetypes=[("Video Files", "*.mp4")])
entry_video.delete(0, tk.END)
entry_video.insert(0, video_path)
def browse_audio():
audio_path = filedialog.asksaveasfilename(defaultextension=".wav", filetypes=[("WAV Files", "*.wav")])
entry_audio.delete(0, tk.END)
entry_audio.insert(0, audio_path)
Creating the Main Window
root = tk.Tk()
root.title("Video to Audio Converter - The Pycodes")
root.geometry("400x200")
root.resizable(False,False)
Here, we created the main window, give it a title (“Video to Audio Converter – The Pycodes“), size and fixed dimensions.
Creating GUI Elements
After that, we create the labels, entry fields, and buttons for video selection, audio file selection, conversion, and status display.
We then organize these elements vertically in the window using the pack method. This approach ensures each component is placed in a logical order, making the interface intuitive and user-friendly. The pack method facilitates automatic alignment and spacing, offering a clean and organized appearance for the GUI.
label_video = tk.Label(root, text="Select Video File:")
label_video.pack()
entry_video = tk.Entry(root, width=40)
entry_video.pack()
button_browse_video = tk.Button(root, text="Browse", command=browse_video)
button_browse_video.pack()
# Audio Entry
label_audio = tk.Label(root, text="Save as Audio File:")
label_audio.pack()
entry_audio = tk.Entry(root, width=40)
entry_audio.pack()
button_browse_audio = tk.Button(root, text="Browse", command=browse_audio)
button_browse_audio.pack()
# Convert Button
button_convert = tk.Button(root, text="Convert to Audio", command=extract_audio)
button_convert.pack()
# Status Label
status_label = tk.Label(root, text="Status: Ready")
status_label.pack()
Main Program Loop
Finally starts the GUI elements and keeps it running in a loop until the user exit the window.
root.mainloop()
Example
Full Code
import tkinter as tk
from tkinter import filedialog
import moviepy.editor as mp
def extract_audio():
video_path = entry_video.get()
audio_path = entry_audio.get()
try:
clip = mp.VideoFileClip(video_path)
audio = clip.audio
# You can customize the audio processing here if needed
# For example, you can apply filters, adjust volume, etc.
audio.write_audiofile(audio_path, codec="pcm_s16le", bitrate="192k", logger=None)
status_label.config(text="Audio extraction complete.")
except Exception as e:
status_label.config(text=f"Error: {str(e)}")
def browse_video():
video_path = filedialog.askopenfilename(filetypes=[("Video Files", "*.mp4")])
entry_video.delete(0, tk.END)
entry_video.insert(0, video_path)
def browse_audio():
audio_path = filedialog.asksaveasfilename(defaultextension=".wav", filetypes=[("WAV Files", "*.wav")])
entry_audio.delete(0, tk.END)
entry_audio.insert(0, audio_path)
# Create main window
root = tk.Tk()
root.title("Video to Audio Converter - The Pycodes")
root.geometry("400x200")
root.resizable(False,False)
# Video Entry
label_video = tk.Label(root, text="Select Video File:")
label_video.pack()
entry_video = tk.Entry(root, width=40)
entry_video.pack()
button_browse_video = tk.Button(root, text="Browse", command=browse_video)
button_browse_video.pack()
# Audio Entry
label_audio = tk.Label(root, text="Save as Audio File:")
label_audio.pack()
entry_audio = tk.Entry(root, width=40)
entry_audio.pack()
button_browse_audio = tk.Button(root, text="Browse", command=browse_audio)
button_browse_audio.pack()
# Convert Button
button_convert = tk.Button(root, text="Convert to Audio", command=extract_audio)
button_convert.pack()
# Status Label
status_label = tk.Label(root, text="Status: Ready")
status_label.pack()
root.mainloop()
Happy Coding!