Difference between revisions of "Convert FLAC to MP3"

From ArchWiki
Jump to: navigation, search
m (Installation)
(41 intermediate revisions by 15 users not shown)
Line 1: Line 1:
[[Category:Development (English)]]
+
[[Category:Audio/Video]]
[[Category: HOWTOs (English)]]
+
[[Category:Scripts]]
[[Category:Package management (English)]]
+
{{Tip|You can use {{AUR|flac2mp3-bash}} script from aur to convert Flac to Mp3 easily.}}
{{i18n_links_start}}
+
{{i18n_entry|English|The_Arch_package_making_HOW-TO_-_with_guidelines}}
+
{{i18n_entry|Русский|The_Arch_package_making_HOW-TO_-_with_guidelines(russian)}}
+
{{i18n_entry|简体中文|The_Arch_package_making_HOW-TO_-_with_guidelines(Chinese)}}
+
{{i18n_links_end}}
+
  
这个文档 [[ABS_-_The_Arch_Build_System | ABS - The Arch Build System]] 提供了一份良好的用于制作和修改 Arch Linux 软件包所需工具和文件的总览。如果你只想要定制或重新编译一个已经存在的软件包,这里应该已经提供了足够的信息。但是,如果你想要制作一个新的软件包,你还需要一些额外的指南。这个文档假定你已经事先阅读并掌握了 ABS 的描述。
+
==Introduction==
 +
Here is a script that will convert FLAC to MP3 via the commandline.
  
==准备文件==
+
Essentially, the .flac files within a directory will be decompressed to .wav and then the resulting .wav files will be encoded to .mp3 using the latest LAME switches for encodings (''-V 0 --vbr-new''). The ID3 tags of the original .flac files will be passed to the resulting .mp3 files.
所有用于制作一个软件包所需的信息放在 <code>PKGBUILD</code>  文件中。当你运行 <code>makepkg</code> 命令,它将在当前工作目录中寻找 <code>PKGBUILD</code> 文件,然后根据 <code>PKGBUILD</code> 文件中的指令编译软件的源代码。当编译成功后,得到的二进制代码,包括诸如包版本和依赖等meta-信息将封装在名叫 <code>name.pkg.tar.gz</code> 的软件包中,你可以使用 <code>pacman -Up <package file></code> 命令将其安装。
+
  
<code>PKGBUILD</code> 文件包含 '''所有''' 用于制作一个软件包所需的指令,这些指令以能够被 bash 识别的的格式存在(don't worry if that little tidbit of clue doesn't help you)。[[ABS_-_The_Arch_Build_System | ABS]] 条目中描述了这里使用的变量,但是最重要的也是最让人迷惑的变量在这里recapped。为了开始制作一个新的包,你应该首先创建一个空的目录,最好取名为 <code>/var/abs/local/<PKGNAME></code>。这样的话,它可以很好的统一到统一的 ABS 树,但如果你没有同步该树的话,cvsup 不会接触(touch)它。进入你新建的目录,创建 <code>PKGBUILD</code> 文件,你可以直接从 <code>/var/abs/PKGBUILD.proto</code> 复制虚构的原型,也可以复制其他软件包的<code>PKGBUILD</code> 。如果你不需创建一个全新的文件,而只需修改其中的编译选项的话,后者是非常合适的选择。
+
The original .flac files will not be harmed and the resulting .mp3s will be in the same directory. All other files in the directory (.nfo, images, .sfv, etc) will be ignored and unharmed.  
  
However you do it, you need a <code>PKGBUILD</code> file to work with here.
+
For more information on LAME switches/settings such as V0, visit [http://wiki.hydrogenaudio.org/index.php?title=LAME Hydrogenaudio LAME Wiki]. V0 is roughly equivalent to ''--preset extreme'' which results in a variable bitrate usually between 220-260. The audio of a V0 is transparent, meaning one cannot tell the difference between the lossy file and the original source (compact disc/lossless), but yet the file size is a quite reasonable.  
  
==Editing of Variables==
+
More information on flac: [http://wiki.hydrogenaudio.org/index.php?title=Flac FLAC]
  
Now open it, and set each of these these variable values depending to the package you are building:
+
===Installation===
<br /><br />
+
*'''pkgname:''' Set this to a name for the package. Convention requests that you use all lower case letters for the package name. It's arbitrary, but it helps if a package's name is equal to the name of the working directory you're in, as well as the filename of the tar.gz that's containing the source of the program you're going to download.
+
  
*'''pkgver:''' Set the version of the package. This can contain letters, numbers and periods, but CANNOT contain a hyphen. It depends on the versioning system (major.minor.bugfix, major.date, etc) that the program you are packaging uses. Again, in most cases you should stick to the version that's part of the sourcepackage filename to make later steps easier and more flexible. Also note: if the package writer uses a dash in their version numbering scheme, replace it with an underscore. ('0.99-10'  =>  '0.99_10')
+
First you need to install the following packages: flac, lame, and id3
  
*'''pkgrel:''' This should be incremented each time you release a package, starting with 1. Its purpose is to differentiate consecutive builds of the same version of a package. Occasionally the first release of a package contains a problem or misfeature. When you make the second release, you increment the <code>pkgrel</code> variable so that pacman knows it needs to be reinstalled. When a new '''version''' of the package is released, you reset the <code>pkgrel</code> variable to 1.
+
<pre>
 +
pacman -S flac lame id3
 +
</pre>
  
*'''pkgdesc:''' This should contain a short, usually less than 76 characters, description of the package. Usually it is not needed repeating the program name. <code>OpenGL accelerated X server</code> is better than <code>xgl is a OpenGL...</code>.
+
Once those are installed, copy the following script into your preferred editor:
  
*'''arch:''' This should contain an array of architectures, usually 'i686', that describes where the PKGBUILD file can be used. You can access this value with the variable <code>$arch</code> during the build.
+
<pre>
 +
#! /bin/sh
  
*'''url:''' This should contain the address of the official site of the program where who is interested can find more informations.
+
for a in *.flac; do
 +
    OUTF=${a%.flac}.mp3
  
*'''license:''' The type of license, if you do not know it please write down 'unknow.'
+
    ARTIST=$(metaflac "$a" --show-tag=ARTIST | sed s/.*=//g)
 +
    TITLE=$(metaflac "$a" --show-tag=TITLE | sed s/.*=//g)
 +
    ALBUM=$(metaflac "$a" --show-tag=ALBUM | sed s/.*=//g)
 +
    GENRE=$(metaflac "$a" --show-tag=GENRE | sed s/.*=//g)
 +
    TRACKNUMBER=$(metaflac "$a" --show-tag=TRACKNUMBER | sed s/.*=//g)
 +
    DATE=$(metaflac "$a" --show-tag=DATE | sed s/.*=//g)
  
*'''depends:''' This should contain an array of package names that need to be installed before this program can be run, separated by spaces. The names can optionally be enclosed in single quotes (apostrophes) to prevent possible shell quoting problems, and the array should be enclosed in round brackets. Sometimes a program requires a minimum version of a dependency; In that case, you might want to use the mathematical "larger or equal than" operator, and enclose the whole construct in quotes. Here's an example to add a dependency on the glibc package, and the slang library of at least version 1.8.0: '''<code>depends('glibc' 'slang>=1.8.0')</code>'''
+
    flac -c -d "$a" | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OUTF"
 +
    id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OUTF"
 +
done
 +
</pre>
  
*'''makedepends:''' This should contain an array of package names that are needed only during the build, but that are unneeded for *using* the package after install. Example: <code>unarj</code> used in a build to unpack some patches.
+
Below is a modified version of the above script which:
 +
* adds an optional parameter (-d), which, if passed on the command line, causes each source FLAC file to be deleted after successful conversion;
 +
* changes the LAME encoding options as follows:
 +
** drops --vbr-new, as it is the default VBR behaviour as of LAME 3.98, and thus is automatically used when "-V 0" is used;
 +
** drops "-m j", as LAME defaults to the specified value (joint stereo) when using --vbr-new (see above);
 +
** drops "-q 0", as LAME defaults to this behaviour when using VBR;
 +
** drops "-s 44.1", as LAME detects the proper sample rate to use;
 +
** adds "--noreplaygain" (personal preference);
 +
* and uses LAME to write tags instead of the id3 package, which has the dual advantage of removing the need for an additional package in the tool chain and allowing the script to write both id3v1 and id3v2 tags (the id3 package does not support id3v2 tags).
  
*'''provides:''' This should contain an array of package names that become unneeded with described one since it gives at least the same features.
+
Now for the script:
  
*'''conflicts:''' This should be an array of package names that if installed with the described one will give problems.
+
<pre>
 +
#! /bin/sh
  
*'''replaces:''' This should be an array of obsolete package names that are replaced by the described one.
+
for a in *.flac; do
 +
    OUTF=${a%.flac}.mp3
  
*'''source:''' This must be an array of files which are needed to build the package, containing at least the location of the program source, which is in most cases a full HTTP or FTP URL enclosed in double quotes. The prototype <code>PKGBUILD</code> shows how you can use the previously set variables for package name and version effectively here. If you find you need to supply files which are not downloadable on the fly, for example self-made patches, you simply put those into the same directory where your <code>PKGBUILD</code> is in, and add the filename to this source array. Any  paths you add here are resolved relative to the directory where the <code>PKGBUILD</code> lies. Before the actual build process is started, all of the files referenced here will be downloaded or checked for existence, and <code>makepkg</code> will not proceed if any are missing.
+
    ARTIST=`metaflac "$a" --show-tag=ARTIST | sed s/.*=//g`
 +
    TITLE=`metaflac "$a" --show-tag=TITLE | sed s/.*=//g`
 +
    ALBUM=`metaflac "$a" --show-tag=ALBUM | sed s/.*=//g`
 +
    GENRE=`metaflac "$a" --show-tag=GENRE | sed s/.*=//g`
 +
    TRACKNUMBER=`metaflac "$a" --show-tag=TRACKNUMBER | sed s/.*=//g`
 +
    DATE=`metaflac "$a" --show-tag=DATE | sed s/.*=//g`
  
*'''md5sums:''' An array of md5 checksums for the source files, space seperated and enclosed in quotes. Once all files in the source array are available, an md5 hash of each file will be automatically generated and compared with the values of this array, '''in the same order they appear in the source array'''. Whilst the order of the source files itself does not matter, it's important that it's coherent with the order of the md5sums, as <code>makepkg</code> won't guess which md5sum belongs to what source file, and will happily start spewing errors if they don't match to prevent download errors or manipulations. You can generate the md5sums array quickly and easily using the command <code>makepkg -g</code> (after the source array has been properly set up) in the directory that contains the <code>PKGBUILD</code>. <code>makepkg -g >>PKGBUILD</code> will generate the sums and append them to the end of the <code>PKGBUILD</code>, from whence you can move the line(s) into the proper position of the file.
+
    flac -c -d "$a" | lame --noreplaygain -V0 \
 +
        --add-id3v2 --pad-id3v2 --ignore-tag-errors --tt "$TITLE" --tn "${TRACKNUMBER:-0}" \
 +
        --ta "$ARTIST" --tl "$ALBUM" --ty "$DATE" --tg "${GENRE:-12}" \
 +
        - "$OUTF"
 +
    RESULT=$?
 +
    if [ "$1" ] && [ "$1" = "-d" ] && [ $RESULT -eq 0 ]; then
 +
        rm "$a"
 +
    fi
 +
done
 +
</pre>
  
So far you've only been setting up meta-information about the package; Where to get the sources, what the name of the package shall be, etc. The next step is supplying instructions on how to actually ''compile and install'' the program you're intending to pack up.
+
Alternatively, below is a script that will search for all FLAC audio files beyond where the script resides on your filesystem and convert them to MP3; including those pesky filenames with spaces.
  
==Using the source==
+
<pre>
Now you should download the source tarball, extract it, and note all commands needed to compile and install it. The contents of the <code>build()</code> function in your <code>PKGBUILD</code> will do nothing but run exactly these steps again, with a little glue to pack everything up once compilation is done.
+
#! /bin/bash
  
Now you probably need to edit the contents of the build() function in the <code>PKGBUILD</code>. This function uses common shell commands in the bash syntax. The basic purpose of this function is to automatically compile the programs and create a <code>pkg</code> directory to install the program to, allowing <code>makepkg</code> to pack it all up easily without having to pick all interesting files from your "live" filesystem.
+
find . -type f -name "*.flac" -print0 | while read -d $'\0' a
===The build() function===
+
Usually the first step in the build function is to change into one of the directories created by uncompressing the source files.  You can use the <code>$startdir</code> variable to do this (it refers to the directory that contains the <code>PKGBUILD</code>). You may also use the $pkgname and $pkgver variables that you set earlier. For example, depending on the name of the directory that was uncompressed by makepkg, the first command in your build function might be <code>cd $startdir/src/$pkgname-$pkgver</code>, which happens to be a very common case unless the program's author is a very, very evil person.
+
  
Compiling the programs is the more difficult part. I will assume you managed to compile the program successfully "by hand" here, as all imaginable steps to do this cannot possibly be covered here. That's what the program's author is supposed to write README and INSTALL files for after all.
+
do
 +
    OUTF=${a%.flac}.mp3
  
Now that you are in that directory, you need to issue whatever commands it takes to compile the files. In simple cases, you may simply use <code>./configure; make</code>, although there are dozens of variations including <code>ant build</code> or issuing the actual <code>gcc</code> commands to compile the packages.
+
    ARTIST=`metaflac "$a" --show-tag=ARTIST | sed s/.*=//g`
 +
    TITLE=`metaflac "$a" --show-tag=TITLE | sed s/.*=//g`
 +
    ALBUM=`metaflac "$a" --show-tag=ALBUM | sed s/.*=//g`
 +
    GENRE=`metaflac "$a" --show-tag=GENRE | sed s/.*=//g`
 +
    TRACKNUMBER=`metaflac "$a" --show-tag=TRACKNUMBER | sed s/.*=//g`
 +
    DATE=`metaflac "$a" --show-tag=DATE | sed s/.*=//g`
  
Good thing is, if you already managed to compile the package manually, you basically only need to list the commands you used here, and things should work out just fine. Since many packages like to install their files relative to the <code>/usr/local</code> directory, but Arch Linux prefers using just <code>/usr</code>, you probably want to supply a parameter to the configure script or the make command to take care of this. The prototype <code>PKGBUILD</code> serves as an example for that. It might work differently, though; Again, your mileage may vary.
+
    flac -c -d "$a" | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OUTF"
 +
    id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OUTF"
 +
done
 +
</pre>
  
The next step in the <code>build()</code> function is to put the compiled files in a place where <code>makepkg</code> can scoop them up to create a package. This directory is the <code>pkg</code> directory. It is supposed to imitate the root of your filesystem to the program's installation procedure. Any files that should be installed in a directory in the root of your filesystem should go in the <code>pkg</code> directory under the same directory structure (ie. if you want to install the file <code>myprog</code> in <code>/usr/bin</code>, it should be placed in <code>$startdir/pkg/usr/bin</code>). Fortunately, only a few programs require the user to copy dozens of files manually, but they supply some kind of installation procedure instead which is supposed to do that automatically, often invoked by running "make install". It's '''critical''', however, that you find out how to tell this installation procedure that it's supposed to stuff all it's nifty files '''not''' into your /, but into <code>$startdir/pkg/</code> instead! Otherwise you'll end up with an empty package file, and the binaries of the program you installed "correctly" added to your system already. Most of the time you'll have to supply the prefix parameter to the "make install" call as shown in the prototype, but it's very well possible that the program you're packaging expects an altogether different approach, but here are some hints:
+
Save the script as ''flac2mp3'' and make the script executable:
  
* Sometimes the <code>configure</code> script accepts a prefix property that tells where the files should be installed. You might use <code>./configure --prefix=$startdir/pkg/usr</code> in such configuration, for example.
+
<pre>
 +
chmod a+x flac2mp3
 +
</pre>
  
* Sometimes there is a <code>PREFIX</code> option to append to a <code>make install</code> command. This is sometimes set as a variable, and sometimes set in the command. In worse cases you have to edit the Makefile(s) (or ant build/properties files if the project uses ant) with sed or a patch you'd have to create yourself.
+
As root, copy the script to /usr/local/bin (or anywhere else that is in your $PATH).
  
* There might be other sorts of install scripts that allow you to specify where the program should be installed.
+
<pre>
 +
cp flac2mp3 /usr/local/bin
 +
</pre>
  
* In some cases, the program expects to be run from a single directory.  Often it is wise to simply copy these to <code>$startdir/pkg/opt</code>.
+
To make /usr/local/bin in your $PATH, do (as normal user):
  
As you might have guessed already, that's the part where actual knowledge and experience becomes a necessity. It helps a lot if you browse over the <code>PKGBUILD</code> files in the ABS tree, as those are tested and contain a few tricks that might prove valuable.
+
<pre>
 +
PATH=$PATH:/usr/local/bin/
 +
</pre>
  
More often that not, the installation routine of the program will take care to create any subdirectories below the <code>pkg/</code> directory. If it does not, however, you'll get a lot of errors during the install stage as files are copied to nonexistent subdirectories. In that case you'll have to create the needed subdirectories by adding the appropriate <code>mkdir</code> commands in the <code>build()</code> function before running the installation procedure. The actual directory structure is package dependent, of course; some programs need to place files in <code>/etc</code> or <code>/usr</code> while others might need to use <code>/bin</code> or <code>/opt</code>.  Most will need to create several directories.  You can do all of this with the <code>mkdir -p $startdir/pkg/OTHER/DIRS/AS/NEEDED</code> command, where OTHER/DIRS/AS/NEEDED represent directories at the root of the filesystem.
+
and then (as normal user):
 +
<pre>
 +
nano .bashrc
 +
</pre>
  
==Testing the PKGBUILD==
+
and add ''export PATH=$PATH:/usr/local/bin/''
  
As you are writing the <code>PKGBUILD</code>'s <code>build()</code> function, you will want to test your changes frequently to ensure there are no bugs. You can do this using the <code>makepkg</code> command in the directory containing the <code>PKGBUILD</code>. With a properly formatted <code>PKGBUILD</code>, this will create a package, but with a broken or unfinished one it will throw an error. Hopefully it will be a descriptive error!
+
====Usage====
  
If running <code>makepkg</code> finished successfully, it will place a shiny new file called $pkgname-$pkgver.pkg.tar.gz in your working directory. This is a pacman package and can be installed with the <code>pacman -U</code> and <code>pacman -A</code> options, or added to a local or web based repository.  Note that just because a package file was built it doesn't mean it works!  It might conceivably contain only the directory structure and no files whatsoever if, for example, you specified a prefix improperly. You can use pacman's query functions to display a list of files contained in the package and the dependencies it requires, and compare those with what you consider as correct. "pacman -Qlp <package file>" and "pacman -Qip <package file>" do the trick.
+
Open up a terminal and cd to the directory of .flac files that you wish to convert and enter ''flac2mp3''
  
If the package looks sane, that's all you need to do. However, if you plan on releasing the package or PKGBUILD, it is imperative that you check and double check and re-double-check the contents of the depends array. This should contain a list of all packages that need to be installed in order for your package to work. You only need to list first level depends in the depends array. That is, you do not need to list packages that your program depends on if other packages that your program depends on are already listed.
+
You'll see the verbose decoding/encoding process in the terminal which may take a few moments.  
  
For example, <code>gtk2</code> depends on <code>glib2</code>. Like most open source C programs, it also requires <code>glibc</code> to be installed. However, <code>glibc</code> does not need to be listed as a dependency for <code>gtk2</code> because it is a dependency for <code>glib2</code>, and <code>glib2</code> is already listed in <code>gtk2</code>.
+
Done.
  
There are some tools you can use to check dependencies, including Jason Chu's famous <code>namcap</code> program (<code>pacman -Sy namcap</code>), and the more arcane <code>ldd</code> program.  Check the man pages for these programs and the links at the end of this document for more information.  You should also scour the program's documentation and website (some nice developers have a page called "dependencies" that helps a lot).
+
====Addendum====
==Testing the package==
+
Also make sure that the package binaries actually ''run'' flawlessly! It's really annoying to release a package that contains all necessary files, but dumps core because of some obscure configuration option that doesn't quite work well with the rest of the system. If you're only going to compile packages for your own system, though, you don't need to worry too much about this quality assurance step, as you're the only person suffering from mistakes after all.
+
  
==To sum it all up==
+
With a small modification the command file can be used to transcode the files into a new directory structure:
* Download the source tarball of the program you want to package up
+
<pre>
* Try compiling the package and installing it into an arbitrary directory
+
#! /bin/bash
* Copy over the prototype <code>/var/abs/PKGBUILD.proto</code> and rename it to <code>PKGBUILD</code> in a temporary working directory
+
find "$1" -name *.flac -print0 | while read -d $'\0' IF
* Edit the PKGBUILD according to the needs of your package
+
do
* Run <code>makepkg</code> and see whether the resulting package is built correctly
+
  OF=$(echo "$IF" | sed -e 's/\.flac$/.mp3/g' -e "s,$1,$2,g")
* If not, repeat the last two steps
+
  echo "$IF -> $OF"
 +
  mkdir -p "${OF%/*}"
  
==Useful links==
+
  ARTIST=`metaflac "$IF" --show-tag=ARTIST | sed s/.*=//g`
* [[ABS_-_The_Arch_Build_System | ABS - The Arch Build System]]
+
  TITLE=`metaflac "$IF" --show-tag=TITLE | sed s/.*=//g`
* [http://www.archlinux.org/pacman/makepkg.8.html makepkg man page]
+
  ALBUM=`metaflac "$IF" --show-tag=ALBUM | sed s/.*=//g`
* [http://bbs.archlinux.org/viewtopic.php?t=4 about dependencies]
+
  GENRE=`metaflac "$IF" --show-tag=GENRE | sed s/.*=//g`
* [http://bbs.archlinux.org/viewtopic.php?t=1590 makepkg tutorial]
+
  TRACKNUMBER=`metaflac "$IF" --show-tag=TRACKNUMBER | sed s/.*=//g`
* [[PKGBUILD help|PKGBUILD Help]]
+
  DATE=`metaflac "$IF" --show-tag=DATE | sed s/.*=//g`
* [[Arch CVS & SVN PKGBUILD guidelines]]
+
  
==Warnings==
+
  flac -c -d "$IF" 2> /dev/null | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OF" 2> /dev/null
* Before you can automate the package building process, you should have done it manually at least once unless you know ''exactly'' what you're doing ''in advance'', in which case you would not be reading this in the first place. Unfortunately, although a good bunch of program authors stick to the 3-step build cycle of "./configure; make; make install", this is not always the case, and things can get real ugly if you have to apply patches to make everything work at all. Rule of thumb: If you can't get the program to compile from the source tarball, and make it install itself to a defined, temporary subdirectory, you don't even need to try packaging it. There isn't any magic pixie dust in <code>makepkg</code> that makes source problems go away.
+
  id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OF"
* In a few cases, the packages are not even available as source and you have to use something like <code>sh installer.run</code> to get it to work. You will have to do quite a bit of research (read READMEs, INSTALL instructions, man pages, perhaps ebuilds from gentoo or other package installers, possibly even the MAKEFILEs or source code) to get it working. In some really bad cases, you have to edit the source files to get it to work at all. However, <code>makepkg</code> needs to be completely autonomous, with no user input. Therefore if you need to edit the Makefiles, you may have to bundle a custom patch with the <code>PKGBUILD</code> and install it from inside the <code>build()</code> function, or you might have to issue some <code>sed</code> commands from inside the <code>build()</code> function.
+
done
* Note that just because a package file was built it doesn't mean it works!  It might conceivably contain only the directory structure and no files whatsoever if, for example, you specified a prefix improperly. You can use pacman's query functions to display a list of files contained in the package and the dependencies it requires, and compare those with what you consider as correct. "pacman -Qlp <package file>" and "pacman -Qip <package file>" do the trick.
+
</pre>
 +
if saved in flac2mp3 this can be used as follows
 +
<pre>./flac2mp3 /srv/media/music /srv/media/music-lofi</pre>
 +
which will take the directory structure under /srv/media/music and transcode its content into /srv/media/music-lofi.
 +
 
 +
With some more tweaks the script will support directories that contain '.' (dots) somewhere in the path and
 +
executing the script from folders that contain 'flac' files
 +
 
 +
Also made specifying an alternate folder location optional
 +
<pre>
 +
#! /bin/bash
 +
find "$1" -name "*.flac" -print0 | while read -d $'\0' IF
 +
do
 +
  if [ "$2" != "" ]
 +
  then
 +
    OF="${IF%.flac}.mp3"
 +
    OF="$2/${OF##*/}"
 +
  else
 +
    OF="${IF%.flac}.mp3"
 +
  fi
 +
  echo "$IF -> $OF"
 +
  mkdir -p "${OF%/*}"
 +
 
 +
  ARTIST=`metaflac "$IF" --show-tag=ARTIST | sed s/.*=//g`
 +
  TITLE=`metaflac "$IF" --show-tag=TITLE | sed s/.*=//g`
 +
  ALBUM=`metaflac "$IF" --show-tag=ALBUM | sed s/.*=//g`
 +
  GENRE=`metaflac "$IF" --show-tag=GENRE | sed s/.*=//g`
 +
  TRACKNUMBER=`metaflac "$IF" --show-tag=TRACKNUMBER | sed s/.*=//g`
 +
  DATE=`metaflac "$IF" --show-tag=DATE | sed s/.*=//g`
 +
 
 +
  flac -c -d "$IF" 2> /dev/null | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OF" 2> /dev/null
 +
  id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OF"
 +
done
 +
</pre>
 +
if saved in flac2mp3 this can be used as follows
 +
<pre>./flac2mp3 /srv/media.store/music /srv/media/music-lofi</pre>
 +
or
 +
<pre>./flac2mp3 /srv/media.store/music </pre>
 +
 
 +
=====Nautilus-scripts=====
 +
 
 +
Here's a well-written version of "flac2mp3" script which will run either from command line or, if you copy it into <tt>~/.gnome2/nautilus-scripts</tt>, it will appear in the right-click menu in Nautilus:
 +
<pre>
 +
#!/bin/bash
 +
#
 +
# Copyright 2008 Octavio Ruiz
 +
# Distributed under the terms of the GNU General Public License v3
 +
# $Header: $
 +
#
 +
# Yet Another FLAC to MP3 script
 +
#
 +
# Author:
 +
# Octavio Ruiz (Ta^3) <tacvbo@tacvbo.net>
 +
# Thanks:
 +
# Those comments at:
 +
# http://www.linuxtutorialblog.com/post/solution-converting-flac-to-mp3
 +
# WebPage:
 +
# https://github.com/tacvbo/yaflac2mp3/tree
 +
#
 +
# This program is distributed in the hope that it will be useful,
 +
# but WITHOUT ANY WARRANTY. YOU USE AT YOUR OWN RISK. THE AUTHOR
 +
# WILL NOT BE LIABLE FOR DATA LOSS, DAMAGES, LOSS OF PROFITS OR ANY
 +
# OTHER KIND OF LOSS WHILE USING OR MISUSING THIS SOFTWARE.
 +
# See the GNU General Public License for more details.
 +
#
 +
# Modified by woohoo
 +
#
 +
# you need zenity package for notifications.
 +
# please note that you can put this script in ~/.gnome2/nautilus-scripts
 +
# and it will show up in right-click menu in any folder in gnome.
 +
#
 +
# modify the lame options to your preference example change -b 320 to -b 128 or -b 192 or -b 256
 +
# LAME_OPTS="--vbr-new -V 0 -b 256"
 +
# LAME_OPTS="-V 0 --vbr-new"
 +
 
 +
LAME_OPTS="-b 320 -h --cbr"
 +
 
 +
old_IFS=${IFS}
 +
IFS='
 +
'
 +
 
 +
# when running from nautilus-scripts, it useful to find the current folder
 +
base="`echo $NAUTILUS_SCRIPT_CURRENT_URI | cut -d'/' -f3- | sed 's/%20/ /g'`"
 +
if [ -z "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" ]; then
 +
  dir="$base"
 +
else
 +
  while [ ! -z "$1" -a ! -d "$base/$1" ]; do shift; done
 +
  dir="$base/$1"
 +
fi
 +
 
 +
if [ "$dir" != "" ]; then
 +
  cd "$dir"
 +
fi
 +
 
 +
id3v2=$(which id3v2)
 +
 
 +
files=`find . -type f -regex '^.+\.flac$' | sort`
 +
 
 +
declare -i nn=0
 +
for file in ${files}
 +
do
 +
  fn=$(readlink -f "$file")
 +
  vars=( `metaflac --no-utf8-convert --export-tags-to=- "${fn}"` )
 +
 
 +
  for N_vars in ${!vars[@]}
 +
  do
 +
    export "$(echo "${vars[${N_vars}]%=*}" | tr [:upper:] [:lower:])=${vars[${N_vars}]#*=}"
 +
  done
 +
 
 +
  dest=`echo "$fn"|sed -e 's/\.flac$/\.mp3/'`
 +
 
 +
  flac -dc "$fn" |\
 +
    lame --ignore-tag-errors --add-id3v2 ${LAME_OPTS} \
 +
        ${artist:+--ta} ${artist} \
 +
        ${tracknumber:+--tn} ${tracknumber} \
 +
        ${title:+--tt} ${title} \
 +
        ${album:+--tl} ${album} \
 +
        ${date:+--ty} ${date} \
 +
        ${genre:+--tg} ${genre} \
 +
        ${comment:+--tc} ${comment} \
 +
        - $dest
 +
 +
    [[ -x ${id3v2} ]] && ${id3v2} \
 +
        ${artist:+--artist} ${artist} \
 +
        ${tracknumber:+--track} ${tracknumber} \
 +
        ${title:+--song} ${title} \
 +
        ${album:+--album} ${album} \
 +
        ${date:+--year} ${date} \
 +
        ${genre:+--genre} ${genre} \
 +
        ${comment:+--comment} ${comment} \
 +
        $dest
 +
 
 +
  let nn=nn+1
 +
done
 +
 
 +
zenity --notification --text "Finished converting flac to mp3.${IFS}Processed ${nn} files."
 +
#zenity --info --text "Done!"
 +
IFS=${old_IFS}
 +
 
 +
</pre>
 +
 
 +
More such conversion scripts on pastebin.com [http://pastebin.com/u/woohoo here].
 +
 
 +
==More generic solution==
 +
 
 +
See [[Convert_Any_To_Mp3]] for a more generic solution if you want to transform to mp3 all kind of audio formats supported by both mplayer and mutagen.

Revision as of 07:13, 17 June 2013

Tip: You can use flac2mp3-bashAUR script from aur to convert Flac to Mp3 easily.

Introduction

Here is a script that will convert FLAC to MP3 via the commandline.

Essentially, the .flac files within a directory will be decompressed to .wav and then the resulting .wav files will be encoded to .mp3 using the latest LAME switches for encodings (-V 0 --vbr-new). The ID3 tags of the original .flac files will be passed to the resulting .mp3 files.

The original .flac files will not be harmed and the resulting .mp3s will be in the same directory. All other files in the directory (.nfo, images, .sfv, etc) will be ignored and unharmed.

For more information on LAME switches/settings such as V0, visit Hydrogenaudio LAME Wiki. V0 is roughly equivalent to --preset extreme which results in a variable bitrate usually between 220-260. The audio of a V0 is transparent, meaning one cannot tell the difference between the lossy file and the original source (compact disc/lossless), but yet the file size is a quite reasonable.

More information on flac: FLAC

Installation

First you need to install the following packages: flac, lame, and id3

pacman -S flac lame id3

Once those are installed, copy the following script into your preferred editor:

#! /bin/sh

for a in *.flac; do
    OUTF=${a%.flac}.mp3

    ARTIST=$(metaflac "$a" --show-tag=ARTIST | sed s/.*=//g)
    TITLE=$(metaflac "$a" --show-tag=TITLE | sed s/.*=//g)
    ALBUM=$(metaflac "$a" --show-tag=ALBUM | sed s/.*=//g)
    GENRE=$(metaflac "$a" --show-tag=GENRE | sed s/.*=//g)
    TRACKNUMBER=$(metaflac "$a" --show-tag=TRACKNUMBER | sed s/.*=//g)
    DATE=$(metaflac "$a" --show-tag=DATE | sed s/.*=//g)

    flac -c -d "$a" | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OUTF"
    id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OUTF"
done

Below is a modified version of the above script which:

  • adds an optional parameter (-d), which, if passed on the command line, causes each source FLAC file to be deleted after successful conversion;
  • changes the LAME encoding options as follows:
    • drops --vbr-new, as it is the default VBR behaviour as of LAME 3.98, and thus is automatically used when "-V 0" is used;
    • drops "-m j", as LAME defaults to the specified value (joint stereo) when using --vbr-new (see above);
    • drops "-q 0", as LAME defaults to this behaviour when using VBR;
    • drops "-s 44.1", as LAME detects the proper sample rate to use;
    • adds "--noreplaygain" (personal preference);
  • and uses LAME to write tags instead of the id3 package, which has the dual advantage of removing the need for an additional package in the tool chain and allowing the script to write both id3v1 and id3v2 tags (the id3 package does not support id3v2 tags).

Now for the script:

#! /bin/sh

for a in *.flac; do
    OUTF=${a%.flac}.mp3

    ARTIST=`metaflac "$a" --show-tag=ARTIST | sed s/.*=//g`
    TITLE=`metaflac "$a" --show-tag=TITLE | sed s/.*=//g`
    ALBUM=`metaflac "$a" --show-tag=ALBUM | sed s/.*=//g`
    GENRE=`metaflac "$a" --show-tag=GENRE | sed s/.*=//g`
    TRACKNUMBER=`metaflac "$a" --show-tag=TRACKNUMBER | sed s/.*=//g`
    DATE=`metaflac "$a" --show-tag=DATE | sed s/.*=//g`

    flac -c -d "$a" | lame --noreplaygain -V0 \
        --add-id3v2 --pad-id3v2 --ignore-tag-errors --tt "$TITLE" --tn "${TRACKNUMBER:-0}" \
        --ta "$ARTIST" --tl "$ALBUM" --ty "$DATE" --tg "${GENRE:-12}" \
        - "$OUTF"
    RESULT=$?
    if [ "$1" ] && [ "$1" = "-d" ] && [ $RESULT -eq 0 ]; then
        rm "$a"
    fi
done

Alternatively, below is a script that will search for all FLAC audio files beyond where the script resides on your filesystem and convert them to MP3; including those pesky filenames with spaces.

#! /bin/bash

find . -type f -name "*.flac" -print0 | while read -d $'\0' a

do
    OUTF=${a%.flac}.mp3

    ARTIST=`metaflac "$a" --show-tag=ARTIST | sed s/.*=//g`
    TITLE=`metaflac "$a" --show-tag=TITLE | sed s/.*=//g`
    ALBUM=`metaflac "$a" --show-tag=ALBUM | sed s/.*=//g`
    GENRE=`metaflac "$a" --show-tag=GENRE | sed s/.*=//g`
    TRACKNUMBER=`metaflac "$a" --show-tag=TRACKNUMBER | sed s/.*=//g`
    DATE=`metaflac "$a" --show-tag=DATE | sed s/.*=//g`

    flac -c -d "$a" | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OUTF"
    id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OUTF"
done

Save the script as flac2mp3 and make the script executable:

chmod a+x flac2mp3

As root, copy the script to /usr/local/bin (or anywhere else that is in your $PATH).

cp flac2mp3 /usr/local/bin

To make /usr/local/bin in your $PATH, do (as normal user):

PATH=$PATH:/usr/local/bin/

and then (as normal user):

nano .bashrc

and add export PATH=$PATH:/usr/local/bin/

Usage

Open up a terminal and cd to the directory of .flac files that you wish to convert and enter flac2mp3

You'll see the verbose decoding/encoding process in the terminal which may take a few moments.

Done.

Addendum

With a small modification the command file can be used to transcode the files into a new directory structure:

#! /bin/bash
find "$1" -name *.flac -print0 | while read -d $'\0' IF
do
  OF=$(echo "$IF" | sed -e 's/\.flac$/.mp3/g' -e "s,$1,$2,g")
  echo "$IF -> $OF"
  mkdir -p "${OF%/*}"

  ARTIST=`metaflac "$IF" --show-tag=ARTIST | sed s/.*=//g`
  TITLE=`metaflac "$IF" --show-tag=TITLE | sed s/.*=//g`
  ALBUM=`metaflac "$IF" --show-tag=ALBUM | sed s/.*=//g`
  GENRE=`metaflac "$IF" --show-tag=GENRE | sed s/.*=//g`
  TRACKNUMBER=`metaflac "$IF" --show-tag=TRACKNUMBER | sed s/.*=//g`
  DATE=`metaflac "$IF" --show-tag=DATE | sed s/.*=//g`

  flac -c -d "$IF" 2> /dev/null | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OF" 2> /dev/null
  id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OF"
done

if saved in flac2mp3 this can be used as follows

./flac2mp3 /srv/media/music /srv/media/music-lofi

which will take the directory structure under /srv/media/music and transcode its content into /srv/media/music-lofi.

With some more tweaks the script will support directories that contain '.' (dots) somewhere in the path and executing the script from folders that contain 'flac' files

Also made specifying an alternate folder location optional

#! /bin/bash
find "$1" -name "*.flac" -print0 | while read -d $'\0' IF
do
  if [ "$2" != "" ]
  then
     OF="${IF%.flac}.mp3"
     OF="$2/${OF##*/}"
  else
     OF="${IF%.flac}.mp3"
  fi
  echo "$IF -> $OF"
  mkdir -p "${OF%/*}"

  ARTIST=`metaflac "$IF" --show-tag=ARTIST | sed s/.*=//g`
  TITLE=`metaflac "$IF" --show-tag=TITLE | sed s/.*=//g`
  ALBUM=`metaflac "$IF" --show-tag=ALBUM | sed s/.*=//g`
  GENRE=`metaflac "$IF" --show-tag=GENRE | sed s/.*=//g`
  TRACKNUMBER=`metaflac "$IF" --show-tag=TRACKNUMBER | sed s/.*=//g`
  DATE=`metaflac "$IF" --show-tag=DATE | sed s/.*=//g`

  flac -c -d "$IF" 2> /dev/null | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OF" 2> /dev/null
  id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OF"
done

if saved in flac2mp3 this can be used as follows

./flac2mp3 /srv/media.store/music /srv/media/music-lofi

or

./flac2mp3 /srv/media.store/music 
Nautilus-scripts

Here's a well-written version of "flac2mp3" script which will run either from command line or, if you copy it into ~/.gnome2/nautilus-scripts, it will appear in the right-click menu in Nautilus:

#!/bin/bash
#
# Copyright 2008 Octavio Ruiz
# Distributed under the terms of the GNU General Public License v3
# $Header: $
#
# Yet Another FLAC to MP3 script
#
# Author:
# Octavio Ruiz (Ta^3) <tacvbo@tacvbo.net>
# Thanks:
# Those comments at:
# http://www.linuxtutorialblog.com/post/solution-converting-flac-to-mp3
# WebPage:
# https://github.com/tacvbo/yaflac2mp3/tree
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY. YOU USE AT YOUR OWN RISK. THE AUTHOR
# WILL NOT BE LIABLE FOR DATA LOSS, DAMAGES, LOSS OF PROFITS OR ANY
# OTHER KIND OF LOSS WHILE USING OR MISUSING THIS SOFTWARE.
# See the GNU General Public License for more details.
#
# Modified by woohoo
#
# you need zenity package for notifications.
# please note that you can put this script in ~/.gnome2/nautilus-scripts
# and it will show up in right-click menu in any folder in gnome.
#
# modify the lame options to your preference example change -b 320 to -b 128 or -b 192 or -b 256
# LAME_OPTS="--vbr-new -V 0 -b 256"
# LAME_OPTS="-V 0 --vbr-new"

LAME_OPTS="-b 320 -h --cbr"

old_IFS=${IFS}
IFS='
'

# when running from nautilus-scripts, it useful to find the current folder
base="`echo $NAUTILUS_SCRIPT_CURRENT_URI | cut -d'/' -f3- | sed 's/%20/ /g'`"
if [ -z "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" ]; then
  dir="$base"
else
  while [ ! -z "$1" -a ! -d "$base/$1" ]; do shift; done
  dir="$base/$1"
fi

if [ "$dir" != "" ]; then
  cd "$dir"
fi

id3v2=$(which id3v2)

files=`find . -type f -regex '^.+\.flac$' | sort`

declare -i nn=0
for file in ${files}
do
  fn=$(readlink -f "$file")
  vars=( `metaflac --no-utf8-convert --export-tags-to=- "${fn}"` )

  for N_vars in ${!vars[@]}
  do
    export "$(echo "${vars[${N_vars}]%=*}" | tr [:upper:] [:lower:])=${vars[${N_vars}]#*=}"
  done

  dest=`echo "$fn"|sed -e 's/\.flac$/\.mp3/'`

  flac -dc "$fn" |\
    lame --ignore-tag-errors --add-id3v2 ${LAME_OPTS} \
        ${artist:+--ta} ${artist} \
        ${tracknumber:+--tn} ${tracknumber} \
        ${title:+--tt} ${title} \
        ${album:+--tl} ${album} \
        ${date:+--ty} ${date} \
        ${genre:+--tg} ${genre} \
        ${comment:+--tc} ${comment} \
        - $dest
 
    [[ -x ${id3v2} ]] && ${id3v2} \
        ${artist:+--artist} ${artist} \
        ${tracknumber:+--track} ${tracknumber} \
        ${title:+--song} ${title} \
        ${album:+--album} ${album} \
        ${date:+--year} ${date} \
        ${genre:+--genre} ${genre} \
        ${comment:+--comment} ${comment} \
        $dest

  let nn=nn+1
done

zenity --notification --text "Finished converting flac to mp3.${IFS}Processed ${nn} files."
#zenity --info --text "Done!"
IFS=${old_IFS}

More such conversion scripts on pastebin.com here.

More generic solution

See Convert_Any_To_Mp3 for a more generic solution if you want to transform to mp3 all kind of audio formats supported by both mplayer and mutagen.