Skip to content

Instantly share code, notes, and snippets.

@cukabeka
Last active April 15, 2023 17:13
Show Gist options
  • Save cukabeka/e8931fed7b5248bbdef2e0bce61d04b6 to your computer and use it in GitHub Desktop.
Save cukabeka/e8931fed7b5248bbdef2e0bce61d04b6 to your computer and use it in GitHub Desktop.
FLAC to mp4 converter for SPOTREC downloads
# parameters not working yet, added removal of number prefixes
import os, re
from mutagen import File
from mutagen.mp4 import MP4, MP4Cover
from subprocess import call
input_folder = "flac_to_convert"
output_folder = "mp4"
quality = "320"
output_format = "m4a"
cover_art_type = 3 # 3 is for jpeg cover art
for filename in os.listdir(input_folder):
if filename.endswith(".flac"):
# Remove prefixed numbers
output_filename = re.sub(r'^\d{2,3}\s-\s', '', filename.replace(".flac", "." + output_format))
# Construct the full paths to the input and output files
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, output_filename)
# Use subprocess to call the ffmpeg command to convert the FLAC to M4A
call(["ffmpeg", "-i", input_path, "-c:a", "aac", "-b:a", quality + "k", "-vn", output_path])
# Use Mutagen to add the cover art to the M4A file
m4a_file = MP4(output_path)
cover_art_path = os.path.join(input_folder, filename.replace(".flac", ".jpeg"))
with open(cover_art_path, "rb") as f:
cover_art_data = f.read()
cover_art = MP4Cover(cover_art_data, imageformat=cover_art_type)
m4a_file.tags["covr"] = [cover_art]
m4a_file.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment