Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'd like to use Makefile to convert my flac music into mp3.

The idea is:

  1. have the same directory structure with a different root name

  2. run a simple command to keep the mp3 folder in sync with the source

  3. not bother if I have already or not converted the file: just run make for updating

  4. copy other files (such as covers)

Apparently it was not as difficult but I had some issues with file and directory names. In general album and song names contain many weird characters (spaces,;' and others). After some trials I was able to get something working.

Thus actually this is not exactly an answer, since my solution seems enough generic and it can be applied for other situations (like converting video, pictures and so on) I'd like to share it.

# Generic make file to convert formats
# creates a target directory structure as the source
# (ex: for converting music) 
# 
# WARNING : current limitations:
# does not support ";" in file or dir names
# does not support two consecutive spaces in dir or filename
# (may be others)

# Input/output extension
INTYPE := flac
OUTTYPE := mp3
COPYTYPE := jpg

# Input/output direcory
INDIR  := Musica-Flac
OUTDIR := Musica-Mp3

# Convert commands (find a better solution using a single var)
CONVERT1 := flac -cd
CONVERT2 := lame - -b 320 

# find target by changing dir name and file extension
# replace spaces with escaped spaces
TARGET := $(shell find $(INDIR) -type f -name '*.$(INTYPE)' | \
 sed -e 's/ /\\ /g' -e s/$(INDIR)/$(OUTDIR)/ -e 's/\.$(INTYPE)/.$(OUTTYPE)/')

COPYFILE := $(shell find $(INDIR) -type f -name '*.$(COPYTYPE)' | \
 sed -e 's/ /\\ /g' -e s/$(INDIR)/$(OUTDIR)/)

all : $(TARGET) $(COPYFILE)

space:=
space+=

# Secondary expansion needed to change direcorty
# and to replace spaces with escaped spaces 
# Use quoted variables in commands (to manage spaces) 

.SECONDEXPANSION:
$(TARGET) : %.$(OUTTYPE) : $$(subst $$(OUTDIR),$$(INDIR),$$(subst $$(space),\$$(space),%)).$(INTYPE)
        @mkdir -p "`dirname "$@"`"
        @$(CONVERT1) "$<" | $(CONVERT2) "$@"

.SECONDEXPANSION:
$(COPYFILE) : % : $$(subst $$(OUTDIR),$$(INDIR),$$(subst $$(space),\$$(space),%))
        @mkdir -p "`dirname "$@"`"
        @cp "$<" "$@"

Any feedback or idea for improvement is welcome.

Cheers.

share|improve this question
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.