Skip to content

Instantly share code, notes, and snippets.

@daitomanabe
Last active May 31, 2023 08:22
Show Gist options
  • Save daitomanabe/0d54b1e3eb9ad3646a658a3c0cf66ed1 to your computer and use it in GitHub Desktop.
Save daitomanabe/0d54b1e3eb9ad3646a658a3c0cf66ed1 to your computer and use it in GitHub Desktop.
extract_channels
from pydub import AudioSegment
import sys
import os
def extract_channels(input_file, output_dir):
audio = AudioSegment.from_file(input_file, format="wav")
# Check if the audio is already mono
if audio.channels == 1:
print(f"Ignoring file '{input_file}' as it is already mono")
return
# Split channels
left_channel = audio.split_to_mono()[0]
right_channel = audio.split_to_mono()[1]
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Extract input file name without extension
input_filename = os.path.splitext(os.path.basename(input_file))[0]
# Export left channel
output_file_left = os.path.join(output_dir, input_filename + "_left.wav")
left_channel.export(output_file_left, format="wav")
# Export right channel
output_file_right = os.path.join(output_dir, input_filename + "_right.wav")
right_channel.export(output_file_right, format="wav")
# Get input directory path from command line argument
if len(sys.argv) < 2:
print("Usage: python extract_channels.py <input_directory>")
sys.exit(1)
input_dir = sys.argv[1]
# Set output directory as the same location as the input directory
output_dir = input_dir
# Process each file within the input directory
file_count = 0
for file in os.listdir(input_dir):
if file.endswith(".wav") or file.endswith(".aif"):
input_file = os.path.join(input_dir, file)
extract_channels(input_file, output_dir)
file_count += 1
print(f"Processed file {file_count}/{len(os.listdir(input_dir))}")
print("Extraction complete!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment