Created
February 24, 2024 13:34
-
-
Save basperheim/34261f8659c95f0c011e9dac44b7d37b to your computer and use it in GitHub Desktop.
Extract audio from video files using Python and FFmpeg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import subprocess | |
DRY_RUN = False | |
# Function to find all video files in the current directory | |
def find_video_files(): | |
video_files = [] | |
for file in os.listdir('.'): | |
if file.endswith('.mkv') or file.endswith('.mp4'): | |
video_files.append(file) | |
return video_files | |
# Function to execute FFmpeg command on each video file | |
def process_files(video_files): | |
extractions_completed = 0 | |
for input_file in video_files: | |
file_extension = input_file.split(".")[-1] | |
if '.reduced.' in input_file: | |
print("\n\x1b[33mSkipping:", input_file, "\x1b[37m") | |
continue | |
else: | |
print("\n\x1b[32mEncoding:", input_file, "\x1b[37m") | |
output_audio_file = os.path.splitext(input_file)[0] + '.mp3' | |
ffmpeg_command = [ | |
'ffmpeg', | |
'-y', | |
'-hide_banner', | |
'-i', input_file, | |
'-vn', # Disable video recording | |
'-acodec', 'libmp3lame', # Use MP3 codec for audio | |
'-q:a', '4', # Set MP3 audio quality (0-9, where 0 is the highest quality) | |
output_audio_file | |
] | |
if not DRY_RUN: | |
# Execute FFmpeg command as a subprocess | |
subprocess.run(ffmpeg_command) | |
extractions_completed += 1 | |
print("extractions_completed:", extractions_completed, "\n\n") | |
else: | |
print(ffmpeg_command) | |
# Find all video files in the current directory | |
video_files = find_video_files() | |
if video_files: | |
# Process each video file | |
process_files(video_files) | |
print("Conversion completed successfully.") | |
else: | |
print("No video files found in the current directory.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment