Skip to content

Instantly share code, notes, and snippets.

@r1cc4rd0m4zz4
Created December 17, 2024 12:40
Show Gist options
  • Select an option

  • Save r1cc4rd0m4zz4/3aff26530b59eec400804a6a780b61e0 to your computer and use it in GitHub Desktop.

Select an option

Save r1cc4rd0m4zz4/3aff26530b59eec400804a6a780b61e0 to your computer and use it in GitHub Desktop.
This script compresses audio files in a specified folder using FFmpeg. It reduces the file size by adjusting the bitrate and sample rate.
## Dependencies
#- [FFmpeg](https://ffmpeg.org/download.html): Make sure FFmpeg is installed and accessible from the command line.
## Usage
#```sh
#python ffmpeg.compress.py [input_folder] [--bitrate TARGET_BITRATE] [--sample_rate SAMPLE_RATE]
#python ffmpeg.compress.py ./audio_files --bitrate 128k --sample_rate 44100
import subprocess
import os
import argparse
def compress_audio(input_file, output_file, target_bitrate="64k", sample_rate=16000):
"""
Compress an audio file to reduce its size.
Args:
input_file (str): Path to the input audio file.
output_file (str): Path to the output audio file.
target_bitrate (str): Target audio bitrate (e.g., '64k', '128k', etc.).
sample_rate (int): Audio sample rate in Hz.
"""
try:
# FFmpeg command to compress audio
command = [
"ffmpeg",
"-i", input_file, # Input file
"-b:a", target_bitrate, # Target bitrate
"-ar", str(sample_rate), # Sample rate
"-ac", "1", # Mono (single channel)
output_file # Output file
]
subprocess.run(command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(f"Compression completed: {output_file}")
except subprocess.CalledProcessError as e:
print(f"Error compressing {input_file}: {e}")
def process_folder(input_folder, target_bitrate="64k", sample_rate=16000):
"""
Process all audio files in a folder.
Args:
input_folder (str): Folder containing the audio files.
target_bitrate (str): Target audio bitrate.
sample_rate (int): Audio sample rate in Hz.
"""
if not os.path.exists(input_folder):
print("The specified folder does not exist.")
return
# Create an output folder
output_folder = os.path.join(input_folder, "compressed_files")
os.makedirs(output_folder, exist_ok=True)
# Scan all audio files in the folder
for filename in os.listdir(input_folder):
input_path = os.path.join(input_folder, filename)
# Filter only audio files with specific extensions
if os.path.isfile(input_path) and filename.lower().endswith((".m4a", ".mp3", ".wav", ".aac")):
# Add the .compress suffix before the extension
base_name, ext = os.path.splitext(filename)
output_filename = f"{base_name}.compress{ext}"
output_path = os.path.join(output_folder, output_filename)
# Compress the file
compress_audio(input_path, output_path, target_bitrate, sample_rate)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Compress audio files in a folder.")
parser.add_argument("input_folder", nargs="?", default=".", help="Folder containing the audio files to compress (default: current folder)")
parser.add_argument("--bitrate", default="64k", help="Target audio bitrate (default: 64k)")
parser.add_argument("--sample_rate", type=int, default=16000, help="Audio sample rate in Hz (default: 16000)")
args = parser.parse_args()
print("Starting audio file compression...")
process_folder(args.input_folder, args.bitrate, args.sample_rate)
print("Compression completed for all files.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment