Blog

Thoughts from my daily grind

Script to convert FLAC to MP3

Posted by Ziyan Junaideen |Published: 30 July 2022 |Category: macOS
Flac to MP3 |

Music is an important part of life and not every tune can be found on Apple Music or Spotify. I recently got my hand on a couple of libraries of early 20th century music in the form of FALC lossless audio files. Unfortunately, Apple Music, my preferred media player on Mac, didn't play FLAC files.

The easy solution is to use a different media player. VLC plays just about anything. But I am an "engineer". An engineer never settles for the easy solution. So I decided to convert them to MP3. Conversion also had the advantage of listening to it on my iPhone and iPad.

To make life easy, I wrote a script to convert FLAC music files in a given folder to MP3. This script is not disruptive (doesn't alter your existing files) and instead creates a new file with the .mp3 extension using the popular library ffmpg.

Steps

Install ffmeg if you haven't already: ffmpeg is a suite of software used to manipulate audio video files.

brew install ffmpeg

Then create a file somewhere convenient. I have a folder that is already in the $PATH variable called $HOME/.scripts/. You can have it anywhere. Just make sure to run the script from that folder.

cd /path/to/scipts/folder
touch flac2mp3

Then use your favourite text editor to open the file.

nvim flac2mp3

Add the following lines. Here I am using zsh.

#!/bin/zsh

# Author: Ziyan Junaideen
# Website: www.jdeen.com
# E-mail: ziyan@jdeen.com
# Phone: +94-74-2869900
# Date: 2022-07-30
# Description: FLAC to MP3 conversion script
# Dependencies: ffmpg
# Examples:
#  ./flac2mp3 ~/Music/MyFlacFolder

# The script is intended to convert all flac files in the provided folder to similarly named MP3 files. There is no
# separate output folder. The files will be in the same folder.

FOLDER=$1

# Iterate through each `flac` file in the provided folder
for file in $FOLDER/*.flac
do
    # Get the filename without the extension
    filename=$(basename "$file" .flac)

    # Convert the file
    ffmpeg -i "$file" -acodec libmp3lame -qscale:a 2 "$FOLDER/$filename.mp3"
done

If you are not using zsh, you should change the first line to the following:

#!/bin/zsh

Now save and exit.

Then lets make this file executable.

chmod a+x flac2mp3

Now you can run:

flac2mp3 /path/to/my/library

The first line is the shebang which tells the computer what program to use to run it.

Improvements

There are many improvements I can think of, but this does my job.

I can think of:

  • Support converting a single flac file
  • Support relative folder paths
  • Abstract the ffmpeg output in favour of the scripts own logging

That's it from me. Hope this was helpful.

About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments