index

FLAC to MP3 beets Importer

This bash script was created to:

  1. Convert FLAC files in a folder to 320kbps MP3 files recursively.
  2. Import music albums represented as folders in a given folder into my music library using beets.

Bash Script

#!/bin/bash
# Script to convert FLAC files from a given directory, and then import using beets
# This environment is run from WSL, where beets is running on the host Windows machine (legacy reasons)

default_win_folder="C:\Users\username\Music"
default_wsl_folder="/mnt/c/Users/username/Music"
arr=()

# Function to convert FLAC files to MP3
convert_flac_to_mp3() {
    for item in "${arr[@]}"; do
        flac_file="$item"
        mp3_file="${flac_file%.flac}.mp3"
        echo "Converting: $flac_file -> $mp3_file"
        # ffmpeg conversion command for 320kbps and to keep metadata
        ffmpeg -i "$flac_file" -ab 320k -map_metadata 0 -id3v2_version 3 "$mp3_file"
    done
}

# Clean up FLAC files after converting
delete_old_flac() {
    rm "${arr[@]}"
}

# Function to iterate through subfolders recursively
iterate_subfolders() {
    folder="$1"

    echo "Found Album or Folder: $folder"

    # Iterate through all files and folders in the given folder
    for item in "$folder"/*; do
        if [ -d "$item" ]; then
            # If it's a subfolder, call the function recursively
            iterate_subfolders "$item"
        elif [ -f "$item" ] && [[ "$item" == *.flac ]]; then
            # Add to list of identified FLAC files
            arr+=("$item")
        fi

    done

    if [ -n "$arr" ]; then
        echo "Found the following FLAC files in folder:"
        printf "%s\n" "${arr[@]}"
        read -p "Convert files in folder? (y/n): " choice
        case "$choice" in
            y|Y ) convert_flac_to_mp3; echo "Conversion of files completed for $folder.";;
            * ) echo "Skipping folder: $folder";;
        esac
        read -p "Delete FLAC files in $folder? (y/n): " choice
        case "$choice" in
            y|Y ) delete_old_flac;;
            * ) echo "Skipping folder: $folder";;
        esac

        # Clear array
        arr=()
    else
        echo "No FLAC files found in this folder, skipping."
    fi
}

# Main script

# Ask for the folder path
read -p "Enter directory (1) or use default (0) '$default_wsl_folder'?" choice
case "$choice" in
    0 ) folder_path=$default_wsl_folder;;
    1 ) read -p "Enter the folder path to search for FLAC files: " folder_path;;
    * ) echo "No valid input.";;
esac

# Check if the folder exists
if [ ! -d "$folder_path" ]; then
    echo "Folder not found!"
    exit 1
fi

# Call the function to iterate through subfolders
iterate_subfolders "$folder_path"

# Run beet import
echo "Running beet import $default_win_folder now. You may need to provide some inputs."
powershell.exe "beet import $default_win_folder"