banner
Previous Page
PCLinuxOS Magazine
PCLinuxOS
Article List
Disclaimer
Next Page

MP3 Bitrate Batch Convertor


by Paul Arnote (parnote)

Call me old fashioned if you must, but I usually listen to the radio when I'm driving in my pickup truck. I usually listen to news talk radio, country & western music, and classic rock & roll. The radio in my truck also has a MP3 CD player, as well as USB ports that I have no idea of what to do with (owner's manual? Meh! tl;dr! ... alright ... alright ... I finally read THAT section of the manual from a PDF of my truck's owner's manual that I downloaded online). Every once in a while, when the kids are in the truck and we're all "headed down the highway," I'll put in the MP3 CD I made for my daughter (you can put hours and hours of music on a MP3 CD). It's full of music from some of her favorite movies ... Frozen, Frozen II, Chitty Chitty Bang Bang, Moana, Mary Poppins, and a smattering of some of her favorite pop/rock songs. Those usually are classic rock. Queen and The Beatles are her favorite bands. Hey ... the young girl has GREAT taste!

Well, today it seems like everyone has a podcast. To be perfectly honest, I had no idea how many podcasts are available. So, ok. I'm late to the podcast party. Despite being around for quite a while, I've never jumped on the whole podcast or streaming bandwagon. For a noob like me, the number of podcasts out there is mind numbing. So, especially when I'm listening to news talk radio, someone out there is advertising a podcast on some random topic.

Lately, I've been hearing advertisements for a new (to me anyways) podcast. It sounded like something I might be interested in, full of espionage, intrigue, drama, etc. It's called "The Agent." It's about a KGB agent during the height of the "Cold War," who slipped into the U.S. unnoticed, and managed to blend into the everyday fabric of life while carrying out his KGB tasks. So, I went looking for it.

I was getting pretty discouraged trying to find it. Most of the results I checked initially were from places like iTunes or some other place that wanted you to sign up for an account. iTunes was a no-go, since I run Linux (PCLinuxOS) and Apple doesn't have a Linux client for iTunes. Then, I stumbled on a whole treasure trove of podcasts on iHeart radio ... including the podcast I was searching for. It debuted in late October, 2021, and finished up in January, 2022.

Here is the description for "The Agent" podcast, from iHeart:

The Agent is the remarkable true story of Jack Barsky, the longest-surviving known member of the KGB illegals program operated during the height of the Cold War. Barsky hid in plain sight in America for 10 years, all the while leading dual lives on both sides of the Atlantic Ocean. On one fateful day, he was confronted with an impossible choice. The Agent is a production of Imperative Entertainment in association with Windjoy and is created, written, produced and edited by Jason Hoch. Narration by Alden Ehrenreich. Executive Producers are Jason Hoch, Jack Barsky and Alden Ehrenreich. Original score by Jasha Klebe. Sound engineering and additional editing by Shaine Freeman.

If you have an interest, there's probably a podcast that covers it. There are many "categories" of podcasts. They include politics (of course), crime, fiction, comedy, sports, self-help, finance/money, kids & family, entertainment, food, music, games & hobbies, history, and many, many more.



Having found the podcast I wanted to hear, I proceeded to download the MP3 files of the podcast to my computer. That part was fairly easy, using a browser plugin. For this particular podcast, there are 13 parts, if you include the "trailer" for the podcast.

iHeart and iTunes (the latter of which is pretty much inaccessible to Linux users anyways, as far as I can tell) aren't the only place to grab podcasts from, either. Here are some others:

Stitcher, where I just grabbed another "historical" podcast called "The MLK Tapes" that takes another look at the MLK assasination. From the podcasts I've downloaded thus far, all of the MP3 files from Stitcher are encoded at 192 kbps, which offers great sound fidelity at a smaller file size.

Spotify, of course, is (or should be) familiar to most people. They have a rather extensive collection of podcasts available, covering a wide range of topics and interests. The one podcast (The Trojan Horse Affair, nine episodes total, including the trailer) were all MP3 files at 128 kbps, which offers perfectly acceptable sound fidelity at a reasonable file size.

Google (yes, I know there are a growing number of users who have no interest ... at all ... in using services provided by Google ... so this is for those who are "ok" with using Google services) has a collection of podcasts from all over the internet. From what I can tell, it appears to be a smish-smash collection of podcasts. I've not really found anything here that's unique or exclusive ... yet. Maybe you should think of it as a good starting point when you're not sure what you want to listen to.

Podcasts-Online.org is another "clearing house" of available free podcasts. Like all of the other podcast sites, there are different categories to match up with varied interests.

Tune-In.com, like all of the others, offers a ton of podcasts that are sure to appeal to just about any interest. I downloaded one episode of an ongoing serial podcast, Stuff You Should Know, and found the MP3 file encoded at an acceptable 96 kbps bitrate, with more than adequate sound fidelity.

I would be negligent if I didn't point you to some Linux-themed podcasts, while we're at it. Be sure to explore the shows from our friends at Jupiter Broadcasting. While there, check out both the active shows and the archived shows. The Late Night Linux podcast is from the U.K., and is produced weekly. Another weekly podcast comes from the folks at Destination Linux. For others, just enter "free linux podcasts" in your favorite search engine (the previous link should open a search with DuckDuckGo).

There are literally TONS of free podcasts available. I just searched for "free podcasts" on DuckDuckGo. I'm sure you'll find more than enough podcasts to keep you busy for quite a long time.

Granted, the quality of the podcasts is wide and varied. So, if you don't find what you're looking for right away, keep looking.

Then, it was time to start gathering some information about the MP3 files I downloaded. The first thing I noticed was that, all together, all of the MP3 files for the podcast series I downloaded (The Agent) totalled up to 1.2GB in total file size. My goal is to burn them to a MP3 CD that I can play in my truck so I can listen to it while driving to and from work, or while tooling around town, and 1.2GB of files aren't going to fit on the 700MB of space on a single CD. Now, I know that CDs are so "yesterday" on the technology spectrum, but they work for my intended use.

Digging deeper, I discovered why the files are so "hefty." Using mediainfo from the PCLinuxOS repository (I use the CLI version, since I'm a Xfce desktop user, and I have it tied to a Thunar custom action. The GUI version will also work equally as well.). All of the MP3 files are recorded at the maximum bitrate: 320 kbps at a constant bitrate. That's pretty much the highest quality you can get from a MP3 file.

The easiest way to get these MP3 files to fit onto a single CD is to decrease the bitrate, and "sacrifice" some of the audio quality. For the most part, that quality loss is quite subjective, which is why I say sacrifice in quotes. Technically, I can reduce the bitrate all the way to 128 kbps, and still not notice any loss of quality in the sound fidelity. You can use a $1,000 set of headphones on a $10,000 stereo system, and you might be able to notice a slight degradation in sound fidelity. Plus, we're not talking about Mozart's or Beethoven's lost concerto. We're talking about (mostly) the spoken word with these podcast episodes.



For a quick review on MP3 compression, the higher the bitrate, the higher the quality, the lower the compression, and the larger the resulting files. MP3 is a lossy compression format, which means every time you recompress a MP3 file, you'll lose more and more fidelity from the file. If you want a compression format/algorithm that is lossless, FLAC is your better choice. However, not all digital players can play FLAC formatted audio files, and you will most likely not get the levels of compression to sufficiently shrink the files to fit onto your destination medium (a 700MB CD in our case here).

So, that means that the converse is true. The lower the bitrate, the lower the quality, the higher the compression, and the smaller the resulting files. I'm compressing the podcast MP3 files (one per episode, for a total of 13 files) to fit on a 700MB CD that's going to be played back on my truck's "audio system" while I'm going down the highway, mixed with road noise. For sure, I'm not going to be noticing any loss of sound fidelity.

And, for the sake of review, there are other things that affect the size of MP3 files. First, reducing a stereo audio file to mono will net you huge gains towards a smaller sized file. But who wants to go around listening to something with the fidelity of AM radio? We/I can do better than that. The "normal" (er, most common) sampling frequency is 44.1kHz. DVDs typically use a 48.0kHz sampling frequency, but increasing it only makes a bigger file. Less common is the 32kHz sampling frequency. While we could decrease the sampling frequency to this level, we're not likely to see the sizes of our files shrink dramatically.

Be careful that you don't take your file compression "too far," unless you just really, really have to. Remember, you're still going to want to listen to this, so you don't want to make it difficult to listen to. The trailer file for "The Agent" was originally 6.5MB (with a CBR of 320 kbps). Using the lowest constant bitrate of 32 kbps, I managed to get the file size down to under 850KB. But then again, it also sounds like it. I could have reduced it further by changing it from stereo to mono, and by using a lower sampling frequency. But at 32 kbps, it already sounds pretty rough. The loss of sound fidelity is VERY apparent. The sound is very "tinny," sounds almost robotic, and the loss of dynamic range is very evident. If you keep your bitrate at 128 kbps or higher, you're very unlikely to notice any degradation of sound fidelity. Even though 128 kbps works fine, I like to use 160 or 192 kbps, just to give a little safety buffer to insure more than adequate sound fidelity.

What I was wanting/needing was a quick way to make the conversions. I explored several options from things I had installed from the PCLinuxOS repository. XCFA worked really well, but I didn't like how it was laid out. Audacity did a good job too, provided I wanted to do the conversions one file at a time. But, being the Xfce user that I am, coupled with my liking to tinker with bash scripts, I figured there had to be a way to do it from right within the Thunar file manager that I'm so accustomed to using. So, I set out to create that method.


My Needs

So, I had to first determine exactly what I wanted and needed the script to do. And, had I just stuck to converting a high resolution MP3 file from one constant bitrate to a lower constant bitrate, I'd have been done and moving on in less than 15 minutes. But, nope. I wanted to choose the output directory for the converted files, the bitrate for the converted files, and whether or not I made the MP3 files use a constant bitrate or a variable bitrate.

Variable bitrate (VBR) MP3 files have a bit more efficiency and do more to preserve sound fidelity than a similarly recorded MP3 file at a constant bitrate (CBR). VBR files dynamically raise and lower the bitrate, depending on need, within a target bitrate range. So, silent areas are recorded at lower bitrates, and louder portions are recorded at higher bitrates. The result is higher sound fidelity at lower average bitrates, resulting in smaller files.

The script also needed graphical components, to make it more user friendly. Since my end goal was to make it accessible from inside Thunar by way of a Thunar custom action, I needed the ability to make data entries on the fly, so some kind of GUI interface was necessary. That is accomplished by leveraging zenity to manage the GUI elements.


The Script

So, here's the script. You can also download it from the magazine website. As you can see below, it's very short (less than 50 lines). The download is only 2.6KB in size. The file is named mp3-bitrate-convert.sh.txt. Save it to wherever on your computer you store your bash files. Then, simply remove the .txt file extension, and make the file executable.





Of course, being a bash script, it opens with the typical bash shebang. Line 3 initializes an integer to start counting at 1. This integer will be important later on when displaying the progress dialog box.



Lines 5 - 11 create the dialog box to enter the destination file's directory. In my tests, I saved my files to ./Test1. If the directory entered does not already exist, it will be created. Because the script writes the output file to a new file to avoid overwriting the original file, you can also write the file to the current working directory. Contrary to the instructions in the dialog box, you can enter ./ as the directory to write the new files to.



Lines 13 - 16 create the dialog box that allows the end user to select whether to re-encode the MP3 file as a CBR (constant bitrate) or VBR (variable bitrate) MP3 file. What you choose here determines which of the next two dialogs you are shown.



Lines 17 - 23 manages the dialog box that is displayed if the end user selects to encode the MP3 file with a constant bitrate. There is some instructional text displayed at the top of the dialog box, and all of the common bitrates from 32 kbps to 320 kbps (you may have to scroll the list to see all of the selections). Simply select the bitrate you want to use, and then select the OK button.



Lines 24 - 30 control the dialog box the end user sees if they choose to encode the MP3 file using a variable bitrate. Just like with the CBR dialog box, some instructional text is provided at the top of the dialog window. The selections range from 0 to 9, so you may have to scroll the list to see all options. The default value in this dialog box is Level 2, which provides an average bitrate of 190 kbps, within a range of 170 to 210 kbps.

Lines 32 - 42 is where the magic happens to re-encode the MP3(s) at the new bitrate. Yes, multiple files can be fed to the script at one time, and the code here will process through those MP3 files one by one, until all of the files have been processed. Lines 33 - 35 make sure the file specified actually exists. If it doesn't, the script will exit.

Line 36 sets up the text that will be displayed in the progress dialog box, so you will know where in the process the script is at. This is especially informative when multiple files are being processed and re-encoded.

Line 37 strips the file extension off of the input file, to make it easier for us to rename the output file with information that makes it unique from the original file. This helps ensure that the original file is not overwritten.

Line 38 calls on ffmpeg to perform the conversion on the input file, and to use the libmp3lame codec to encode the MP3 file. The information for the encoding is stored in the $QUAL string, and it is unique to whether the user chooses CBR or VBR to use when encoding the MP3 file. That variable is written into memory when the end user makes their bitrate choice in either the CBR or VBR bitrate selection dialog boxes. Then, the output file is written to the chosen directory, with the base filename, and appended with the bitrate chosen by the end user and the ".mp3" file extension. If you choose the VBR route, the bitrate appended to the end of the filename will be a single digit between 0 and 9. If you choose the CBR route, the bitrate appended to the end of the filename will be either a double or triple digit number that corresponds to the chosen CBR bitrate.



Lines 39 and 40 set and increment the percentage displayed by the progress bar in the progress dialog box. Line 42 completes the for - do loop, and initializes the progress dialog box. Line 44 exits the script when it is complete.


Using The Script

Don't fret if you don't use Xfce or Thunar file manager. This script also runs PERFECTLY from a command line prompt. I have no doubts that it should be able to run from within the Caja file manager on Mate, and with very little trouble from the Dolphin file manager in KDE. Since I really don't use those desktop environments, I won't stumble through trying to tell you how to set those up. I'm no longer familiar enough with them to be able to guide you on an error-free setup when it comes to integrating the script into those file managers' context menus.

To run the script from the command line, simply execute the script with the files you want to re-encode listed as arguments. I store all of my scripts in a /bin directory in my $HOME directory, and that directory has been added to my default $PATH statement. That way, my scripts can be found whenever they are needed, without having to provide a full path to the scripts. I recommend you do the same (it makes life SO much easier).

Similarly, cd to the directory that contains the MP3 files you want to encode. That way, all you have to provide as command line arguments are the filenames. Otherwise, you will need to provide a fully qualified path and filename for each file you want to re-encode. From there, just follow the prompts in the dialog boxes that appear on your screen.

Also, take note that the script will not complete on filenames that contain spaces. In fact, it will fail every single time. I know there's a fix somewhere for this, but I have not implemented it. First, it's too time consuming. The script works exactly as I intend, and accomplishes what I set out to do. Second, it will make the script larger than it needs to be. Third, since I've come to my senses and stopped using Windows, I've come to absolutely hate spaces in filenames. Spaces are commonly used as delimiters for various command arguments in Linux, so the inclusion of spaces in filenames causes unnecessary problems. I have a one-liner bash command that does nothing but replace spaces in filenames with either a dash or a period. I run it from a Thunar custom action, and I use it ... A LOT. The same thing goes for directory names, meaning NO SPACES. So ... strip filenames (and directory names) of spaces before attempting to run this script on your MP3 files, and you'll have no problem.



To set the script up as a Thunar custom action (that appears on the right-click context menu in Thunar), go to the Edit > Configure custom action menu item. In the dialog box that appears, select the "+" icon, and fill out the dialog boxes (pictured above) as shown. For the command on the "Basic" tab, enter mp3-bitrate-convert.sh %N. Under the "Appearance Conditions" tab, place a checkmark next to "Audio files," and enter "*.mp3;*.MP3" on the "File Pattern" line.

Now, whenever you right click on a MP3 file, you will be given the option to select MP3 Bitrate Convertor from the right-click context menu. Even better, if you have a whole bunch of MP3 files to convert (I had 13 to do here), you can select them all and let the MP3 Bitrate Convertor do its job on all of them, one after another, while you go get a cup of coffee and/or a BLT (bacon, lettuce, tomato ... with mayo) sandwich. Follow the dialog prompts, and you will be able to perform the bitrate conversion without ever having to leave Thunar ... and without even launching any other program.


Summary

I love how robust Linux is. If you can think of a problem, you can probably also come up with a way to solve it.

One thing that helped me write this simple bash script so quickly was code reuse. Much of the code that I used in the bash script was taken from other scripts I have written in the past. I just had to take the time to customize and tailor the script code fragments into a cohesive script, and to the task at hand. The only "new" code in the bash script are those customizations that I made to fulfill the task I set out to do. As a bonus, every time I reuse code fragments, I learn something new about how to make it more efficient. This time was no different. It's always a good thing when you learn new things that make things even more efficient. If I can do this, then I'm sure you also can, if you only set your mind to it.



Previous Page              Top              Next Page