Ubuntu – How to convert .mp4 and .m4a files to .mp3 files automatically, keeping the cover art

.mp4itunesm4amp3

I have some .mp4 and .m4a audio files that I want to convert to .mp3 files. I want the resulting .mp3 files to include the cover art included in the source files, without fiddling with EasyTAG manually. How can I do this?

Best Answer

I've written a script that will do this automatically. Just run the script against each .m4a or mp4 file, like this, and it will produce the .mp3 files in the same directory:

convert-mp4-to-mp3.sh *.mp4 *.m4a

You'll need to install these dependencies:

sudo apt-get install realpath libav-tools atomicparsley eyed3

Here's the script. Copy and paste this content and save it to a file named convert-mp4-to-mp3.sh:

#!/bin/bash

set -e

for filename in "$@" ; do
    if [[ "$filename" == -* ]] ; then
        printf "Filename %s must not begin with a dash\n" "$filename" 1>&2
        continue
    fi
    printf "Converting %s\n" "$filename"
    filename=$(realpath "$filename")
    directory=$(mktemp -d)
    cwd=$(pwd)
    output="$(basename "$filename" | sed 's/\.[^.]*$//').mp3"
    cd "$directory"
    avconv -i "$filename" "$output"
    ln -s "$filename" "$(basename "$filename")"
    AtomicParsley "$(basename "$filename")" --extractPix || true
    shopt -s nullglob
    for imagefilename in *.jpg *.png *.JPG *.PNG ; do
        eyeD3 --add-image="$imagefilename":FRONT_COVER "$output" 
        break
    done
    shopt -u nullglob
    mv "$output" "$(dirname "$filename")"
    cd "$cwd"
    rm -r "$directory"
done