perjantai 26. helmikuuta 2010

Converting music to mp3 in place

I bought a new car stereo a while ago. I'm not going to specifics about it as this is not a car hifi blog. What's interesting is that the player can play mp3's from CD, USB memory and SD card.

My digital audio collection is mostly in ogg and flac format for better quality/file size and the player can't handle them. I tried to find a nice solution to mass convert files from ogg/flac to mp3 but none of them were satisfactory so i wrote my own script:


#!/bin/bash
# Convert flac & ogg audio to low quality mp3 for mobile playing.
# By Ville Ranki

find -type f -name "*.flac" -o -name "*.ogg" | while read file
do
outfile=`echo $file | sed 's/\.[^\.]*$/.mp3/'`
echo "Converting $file to $outfile"
gst-launch-1.0 filesrc location="$file" ! decodebin ! audioconvert ! lamemp3enc target=quality quality=4 ! id3v2mux ! filesink location="$outfile"

if [ -f "$outfile" ];
then
   echo "Removing original $file"
   rm "$file"
else
   echo "Error: File $outfile was not created."
fi

done



This script will find recursively all files in current directory, convert them to mp3's (while preserving id3 tags) and delete the original files. It preserves directories as they are - my car player should be able to browse by directory although i haven't figured out how to do so.

I use it by copying wanted music to a temporary directory, run the script in the directory and copy the results to usb stick or other media.

Make sure you have all the commands installed before running the script, such as gst-launch-0.10. Also don't run the script where the original collection is or you'll lose it. Copy files somewhere else first.

I hope this is helpful for others with the same problem.

(Updated 23.7.2015 for gst-launch-1.0 and simplified the script at the same time)

2 kommenttia:

cos kirjoitti...

got an hint from peltzi to fix the file extensions:

$(echo "$file" | sed -e 's/\.ogg/\.mp3$/.mp3/')


I'll add it to the script later.

Henri kirjoitti...

You can also fix the extension without launching external processes using the following parameter expansion:

"${file%.ogg}".mp3

This syntax is part of POSIX sh and works at least on FreeBSD sh and Debian dash, and of course in bash and zsh. Notably it doesn’t seem to work on Solaris 10 sh, however.