#!/bin/bash # This script converts all MP3 or M4A files in a specified source directory to the Opus format, # leveraging parallel processing to speed up the conversion. # Example usage: # convert_to_opus.sh source/trimmed_mp3 source/trimmed_opus 8 # Set the source and destination directories from the command-line arguments. # If no arguments are provided, use default values. SOURCE_DIR=${1:-source/mp3} DEST_DIR=${2:-opus_converted} NUM_JOBS=${3:-$(nproc 2>/dev/null || sysctl -n hw.ncpu)} # Create the output directory. The -p flag ensures that the command doesn't fail if the directory already exists. mkdir -p "$DEST_DIR" export DEST_DIR # Define the conversion function to be run in parallel. convert_to_opus() { f="$1" # Get the base name of the file (e.g., "001.mp3") filename=$(basename -- "$f") # Get the file name without the extension (e.g., "001") filename_noext="${filename%.*}" # Use ffmpeg to convert the file to Opus format. # The output is redirected to /dev/null to prevent ffmpeg from flooding the console. echo "Converting $f to $DEST_DIR/${filename_noext}.opus" ffmpeg -i "$f" -fflags +genpts -c:a libopus -ar 48000 -vbr on -map_metadata -1 -y "$DEST_DIR/${filename_noext}.opus" >/dev/null 2>&1 } export -f convert_to_opus # Find all .mp3 and .m4a files in the source directory and process them in parallel using a while loop. find "$SOURCE_DIR" -type f \( -name "*.mp3" -o -name "*.m4a" \) -print0 | while IFS= read -r -d $'\0' file; do ((i=i%NUM_JOBS)); ((i++==0)) && wait convert_to_opus "$file" & done wait echo "All files have been converted to Opus format and are located in the $DEST_DIR directory."