Skip to content

Instantly share code, notes, and snippets.

@surfaceflinger
Created November 10, 2023 20:52
Show Gist options
  • Save surfaceflinger/012732f0582991c5b8bc7bf84673e0ed to your computer and use it in GitHub Desktop.
Save surfaceflinger/012732f0582991c5b8bc7bf84673e0ed to your computer and use it in GitHub Desktop.
Recursive, "multithreaded" music converter in bash. 1:1 Copies everything that isn't a flac to keep ur box art scans, covers and already lossy files.
#! /usr/bin/env nix-shell
#! nix-shell -i bash -p opusTools
# Set source and target directories
src_dir="/vol/ikea/Media/Music/Ready"
target_dir="/vol/ikea/Media/Music/Essa"
# Number of allowed threads
max_threads=2
# Semaphore function to limit the number of threads
# YES WE HAVE FUCKING SEMAPHORES IN BASH HOLYYYYYYY SHIT
semaphore() {
while [ $(jobs | wc -l) -ge $max_threads ]; do
sleep 1
done
}
# Function to convert FLAC to OGG Opus
convert_flac_to_opus() {
flac_file="$1"
ogg_opus_file="${flac_file%.*}.opus"
opusenc --bitrate 192 "$flac_file" "$ogg_opus_file"
}
# Function to process directories and files
process_directory() {
local src="$1"
local dest="$2"
# Create target directory structure if it doesn't exist
mkdir -p "$dest"
# Loop through files and subdirectories
for file in "$src"/*; do
if [[ -d "$file" ]]; then
# If it's a directory, recursively process it
semaphore
process_directory "$file" "$dest/$(basename "$file")" &
elif [[ "${file##*.}" == "flac" ]]; then
# If it's a FLAC file, convert it to OGG Opus and preserve the directory structure
semaphore
convert_flac_to_opus "$file"
mkdir -p "$dest"
mv "${file%.*}.opus" "$dest" &
else
# If it's not a FLAC file, copy it to the target structure
semaphore
cp "$file" "$dest" &
fi
done
# Wait for all background processes to finish
wait
}
# Run the conversion process
process_directory "$src_dir" "$target_dir"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment