Converting an audio library to mp3
Over the years I had accumulated a number of audio recordings done with Audacity with a mix of formats and quality. I had these stored on a Synology NAS in a deeply nested structure and I wanted to standardise the format to 320kbps mp3 files so I wrote the following script to do so.
The script does the following:
- Traverses a directory tree recursively (using python’s
os.walk
) - Guesses the file type using the
filetype
package (some files had a format that did not match the extension) - If file is OGG, Flac or Wav it triggers ffmpeg to convert it to 320k mp3.
- On success it removes the old file
To set it up, create a file flac_to_mp3.py
with contents:
#!/usr/bin/env python
import os
import sys
import filetype
print('FLAC to MP3 Script')
if len(sys.argv) > 1:
folder = sys.argv[1]
print('Will scan folder ' + folder)
for dirpath, dnames, fnames in os.walk(folder):
for f in fnames:
sys.stdout.write('.')
sys.stdout.flush()
file_path = os.path.join(dirpath, f)
file_kind = filetype.guess(file_path)
if file_kind is None:
continue
elif file_kind.mime == "audio/x-flac" \
or file_kind.mime == "audio/x-wav" \
or file_kind.mime == "audio/ogg":
print('\nConverting: ' + file_kind.mime + ' - ' + file_path)
destination_file = os.path.splitext(file_path)[0] + '.mp3'
os.system("ffmpeg -i \"{0}\" -ab 320k -map_metadata 0 -y -id3v2_version 3 \"{1}\"" \
.format(file_path, destination_file))
os.remove(file_path)
else:
print('Usage: ./flac_to_mp3.py /path/to/folder')
if you are on Linux or OSX give it execution permission:
chmod +x flac_to_mp3.py
And run it:
./flac_to_mp3.py /absolute/path/to/your/audio/directory