Blog

Bulk Converting FLAC Files to MP3

, John Comber

Introduction

I've recently ripped all my CDs to FLAC format using the excellent Exact Audio Copy.

I wanted to keep a local copy of my music library on my phone for listening when out walking, driving, etc.

While the file size of audio stored in the FLAC format is smaller than non-compressed lossless formats (e.g. WAV), it's still around double the size of high quality (320kbps) MP3 files. The quality of 320kbps MP3 files is fine for when I'm walking, driving, etc. as there will always be some background noise.

My phone also has an issue with decoding FLAC files and occasionally skips half a second which is annoying.

So, I looked for a way to bulk convert all the FLAC files to MP3 files. The results of this exercise are below.

Prerequisites

ffmpeg

ffmpeg is an open source audio and video conversion utility. To run it on Windows, you have to either download the source and compile it or download the exe from a mirror site. I wasn't keen on either option so I opted to use an Ubuntu distribution on WSL where ffmpeg is available from the apt source.

sudo apt install ffmpeg

Powershell

I've used Powershell to automate the bulk convert operation. I can work my way around BASH but I find Powershell more intuitive to work with.

Powershell can be downloaded and installed on Linux by following the instructions here.

Powershell Script

$Root = "~/temp"
$SourceRoot = Join-Path $Root "flac"

$SourcePaths = Get-ChildItem -Directory -Recurse $SourceRoot | Select-Object -ExpandProperty FullName


ForEach ($SourcePath in $SourcePaths)
{
    $TargetPath = $SourcePath -replace "flac", "mp3"

    New-Item -ItemType "directory" -Path $TargetPath -ErrorAction SilentlyContinue

    # Get all the files in the source directory.
    $Files = Get-ChildItem -File $SourcePath

    ForEach ($File in $Files)
    {
        if ($File.Extension -eq ".flac")
        {
            # Convert the flac file and save it in the target directory.
            & ffmpeg -i $File.FullName -ab 320k -map_metadata 0 -id3v2_version 3 (Join-Path $TargetPath "$($File.BaseName).mp3")
        }
        else
        {
            # Copy any non flac files (e.g. album art).
            Copy-Item $File -Destination $TargetPath
        }
    }
}

Licence

MIT