After yesterday’s post about a bash script to backup an Android phone, I decided it was time to get around to writing a simple script to convert all of my music CD ripped music to mp3.
In order to keep a permanent digital archive of all of my music over the years, I have been ripping CDs to FLAC files. If you are not familiar with FLAC, it is like MP3 in that it is a compressed music file format, but unlike MP3 in that it is lossless. Since music CDs are uncompressed, any time you convert them to MP3, you lose a little quality. Maybe you don’t care. Particularly if you are okay with crappy headphones or speakers. But if you have a good set of headphones or speakers, you can hear the difference. At least I can. The MP3 compression basically sounds like you are using crappier speakers.
On most songs, it is pretty hard to tell the difference at the lowest compression levels in MP3 (i.e. biggest file size). But on other songs, it can be subtly noticeable.
So I have an old collection of FLAC files from CDs I’ve purchased over the years. But I often listen to music off of my phone (with good headphones) these days which has limited storage space (and the phone probably doesn’t have a good enough DAC to make the difference all that significant).
So how to take about a thousand FLAC files organized by artist and album (done automatically by the ripping software), and convert them into MP3 files in a subdirectory of each album’s FLAC file directory called “mp3”?
Ubuntu and Python make this relatively straightforward. First start off with making sure you have the “avconv” command installed:
sudo apt-get install libav-tools
Then change directory into the parent directory of all of your music, and run this Python script:
#!/usr/bin/env python
import os, subprocess
# recursively walk through all subdirectories
for subdir, dirs, files in os.walk( ‘.’ ):
# loop over files
for f in files:
# check if this is a flac file
if f.endswith( ‘.flac’ ):
# get full path to flac file
flac = os.path.join( subdir, f )
# get pathname to mp3 output file in the mp3 subdirectory
# of flac file directory
mp3dir = os.path.join( subdir, ‘mp3’ )
mp3 = os.path.join( mp3dir, f[:-len(‘.flac’)] + ‘.mp3’ )
# check if mp3 file exists
if not os.path.exists( mp3 ):
# mp3 file does not exist
# make mp3 directory if needed
if not os.path.exists( mp3dir ):
os.mkdir( mp3dir )
# so call avconv to create mp3 file from flac file
subprocess.call( [ ‘avconv’, ‘-i’, flac, ‘-qscale:a’, ‘0’, mp3 ] )