How to normalize sound in mp3 filesAutomatically adjust the volume based on content?Is there a way to have Clementine normalize my music?Rhythmbox: How to normalize song volumes?Normalize all audio files before copying to an iPodBatch normalize audio volume on .ogg-filesNormalising volume on sound filesmp3 quality bad when running on virtualboxNormalize all audio files before copying to an iPodHelp ubuntu sound issuse's (14.4)No Sound In Ubuntu 16.04!Set volume to 150% permanently and map volume keys from 0-150%Reduce the file size of multiple .mp3s of voice recordings via command line at onceCompressor/Limiter for master volumeMerging many MP3 files via command line on Ubuntu

How to pay less tax on a high salary?

Intersection of sorted lists

What is this Kanji? I can’t find it anywhere?

Is the use of ellipsis (...) dismissive or rude?

Can two moons have intersecting orbits yet be guaranteed not to collide?

Is 人孔 from English?

Between while and do in shell script

Feeling of forcing oneself to do something

Is it academically dishonest to submit the same project to two different classes in the same semester?

Why does std::atomic constructor behave different in C++14 and C++17

Why do cargo airplanes fly fewer cycles then airliners?

What are examples of (collections of) papers which "close" a field?

Why are green parties so often opposed to nuclear power?

Did the Windows 95 screensavers use hardware acceleration APIs?

Retracting Recommendation Letters

Does std::unordered_map operator[] do zero-initialization for non-exisiting key?

Why do cargo airlines frequently choose passenger aircraft rather than aircraft designed specifically for cargo?

"Don't invest now because the market is high"

Recommendation for a fixed-step ODE solver?

How could pirates reasonably transport dinosaurs in captivity, some of them enormous, across oceans?

Do Adventure cards count towards "number of instant and sorcery cards in your graveyard"?

Why is inverting op-amp behaving like a low pass filter?

Prefix all commands in shell

What does 36.000€ mean?



How to normalize sound in mp3 files


Automatically adjust the volume based on content?Is there a way to have Clementine normalize my music?Rhythmbox: How to normalize song volumes?Normalize all audio files before copying to an iPodBatch normalize audio volume on .ogg-filesNormalising volume on sound filesmp3 quality bad when running on virtualboxNormalize all audio files before copying to an iPodHelp ubuntu sound issuse's (14.4)No Sound In Ubuntu 16.04!Set volume to 150% permanently and map volume keys from 0-150%Reduce the file size of multiple .mp3s of voice recordings via command line at onceCompressor/Limiter for master volumeMerging many MP3 files via command line on Ubuntu






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









39


















I am looking for a way to normalize the sound in MANY MP3 files I have. Some have low sound, while others are louder so I have to turn the volume up or down depending on the song. What ways are there to do this for all files. I specially would like to do it via the terminal but GUI ways are also accepted.










share|improve this question

























  • For normalizing while playing see: askubuntu.com/questions/95716/…. This will however not change your mp3 file content - may be of advantage ;)

    – Takkat
    Jan 22 '13 at 18:09












  • Not while playing, don't want to have to set it everytime or have a player set the normalize every time I want to listen to the songs. For example, let us say I want to copy the songs to an ipod shuffle or to a pen drive to listen in a mp3 capable player.

    – Luis Alvarado
    Jan 22 '13 at 18:13











  • @Takkat BTW nicely done in that other question. Good information.

    – Luis Alvarado
    Jan 22 '13 at 18:24






  • 1





    My wife just tested the Audacity method, and it worked perfectly! Recommended. Please, when people ask for advice it is because they are NOT experts. So don´t tell them to use command line tools when they can do the job with easy-to-understand graphical tools like Audacity. Telling new Linux users to open terminal and run command line tools will just scare them away from Ubuntu, with a feeling that Windows is simple, Linux is difficult. It is not a surprise that DOS is dead, but Windows is alive.

    – user297240
    Jun 23 '14 at 20:42











  • It's great your wife was able to figure out the graphical way, but did you miss the part where the person asking the question specifically wanted to achieve it via the terminal?

    – RichardP
    Apr 9 '17 at 5:53

















39


















I am looking for a way to normalize the sound in MANY MP3 files I have. Some have low sound, while others are louder so I have to turn the volume up or down depending on the song. What ways are there to do this for all files. I specially would like to do it via the terminal but GUI ways are also accepted.










share|improve this question

























  • For normalizing while playing see: askubuntu.com/questions/95716/…. This will however not change your mp3 file content - may be of advantage ;)

    – Takkat
    Jan 22 '13 at 18:09












  • Not while playing, don't want to have to set it everytime or have a player set the normalize every time I want to listen to the songs. For example, let us say I want to copy the songs to an ipod shuffle or to a pen drive to listen in a mp3 capable player.

    – Luis Alvarado
    Jan 22 '13 at 18:13











  • @Takkat BTW nicely done in that other question. Good information.

    – Luis Alvarado
    Jan 22 '13 at 18:24






  • 1





    My wife just tested the Audacity method, and it worked perfectly! Recommended. Please, when people ask for advice it is because they are NOT experts. So don´t tell them to use command line tools when they can do the job with easy-to-understand graphical tools like Audacity. Telling new Linux users to open terminal and run command line tools will just scare them away from Ubuntu, with a feeling that Windows is simple, Linux is difficult. It is not a surprise that DOS is dead, but Windows is alive.

    – user297240
    Jun 23 '14 at 20:42











  • It's great your wife was able to figure out the graphical way, but did you miss the part where the person asking the question specifically wanted to achieve it via the terminal?

    – RichardP
    Apr 9 '17 at 5:53













39













39









39


13






I am looking for a way to normalize the sound in MANY MP3 files I have. Some have low sound, while others are louder so I have to turn the volume up or down depending on the song. What ways are there to do this for all files. I specially would like to do it via the terminal but GUI ways are also accepted.










share|improve this question














I am looking for a way to normalize the sound in MANY MP3 files I have. Some have low sound, while others are louder so I have to turn the volume up or down depending on the song. What ways are there to do this for all files. I specially would like to do it via the terminal but GUI ways are also accepted.







sound mp3






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 22 '13 at 17:59









Luis AlvaradoLuis Alvarado

179k143 gold badges496 silver badges670 bronze badges




179k143 gold badges496 silver badges670 bronze badges















  • For normalizing while playing see: askubuntu.com/questions/95716/…. This will however not change your mp3 file content - may be of advantage ;)

    – Takkat
    Jan 22 '13 at 18:09












  • Not while playing, don't want to have to set it everytime or have a player set the normalize every time I want to listen to the songs. For example, let us say I want to copy the songs to an ipod shuffle or to a pen drive to listen in a mp3 capable player.

    – Luis Alvarado
    Jan 22 '13 at 18:13











  • @Takkat BTW nicely done in that other question. Good information.

    – Luis Alvarado
    Jan 22 '13 at 18:24






  • 1





    My wife just tested the Audacity method, and it worked perfectly! Recommended. Please, when people ask for advice it is because they are NOT experts. So don´t tell them to use command line tools when they can do the job with easy-to-understand graphical tools like Audacity. Telling new Linux users to open terminal and run command line tools will just scare them away from Ubuntu, with a feeling that Windows is simple, Linux is difficult. It is not a surprise that DOS is dead, but Windows is alive.

    – user297240
    Jun 23 '14 at 20:42











  • It's great your wife was able to figure out the graphical way, but did you miss the part where the person asking the question specifically wanted to achieve it via the terminal?

    – RichardP
    Apr 9 '17 at 5:53

















  • For normalizing while playing see: askubuntu.com/questions/95716/…. This will however not change your mp3 file content - may be of advantage ;)

    – Takkat
    Jan 22 '13 at 18:09












  • Not while playing, don't want to have to set it everytime or have a player set the normalize every time I want to listen to the songs. For example, let us say I want to copy the songs to an ipod shuffle or to a pen drive to listen in a mp3 capable player.

    – Luis Alvarado
    Jan 22 '13 at 18:13











  • @Takkat BTW nicely done in that other question. Good information.

    – Luis Alvarado
    Jan 22 '13 at 18:24






  • 1





    My wife just tested the Audacity method, and it worked perfectly! Recommended. Please, when people ask for advice it is because they are NOT experts. So don´t tell them to use command line tools when they can do the job with easy-to-understand graphical tools like Audacity. Telling new Linux users to open terminal and run command line tools will just scare them away from Ubuntu, with a feeling that Windows is simple, Linux is difficult. It is not a surprise that DOS is dead, but Windows is alive.

    – user297240
    Jun 23 '14 at 20:42











  • It's great your wife was able to figure out the graphical way, but did you miss the part where the person asking the question specifically wanted to achieve it via the terminal?

    – RichardP
    Apr 9 '17 at 5:53
















For normalizing while playing see: askubuntu.com/questions/95716/…. This will however not change your mp3 file content - may be of advantage ;)

– Takkat
Jan 22 '13 at 18:09






For normalizing while playing see: askubuntu.com/questions/95716/…. This will however not change your mp3 file content - may be of advantage ;)

– Takkat
Jan 22 '13 at 18:09














Not while playing, don't want to have to set it everytime or have a player set the normalize every time I want to listen to the songs. For example, let us say I want to copy the songs to an ipod shuffle or to a pen drive to listen in a mp3 capable player.

– Luis Alvarado
Jan 22 '13 at 18:13





Not while playing, don't want to have to set it everytime or have a player set the normalize every time I want to listen to the songs. For example, let us say I want to copy the songs to an ipod shuffle or to a pen drive to listen in a mp3 capable player.

– Luis Alvarado
Jan 22 '13 at 18:13













@Takkat BTW nicely done in that other question. Good information.

– Luis Alvarado
Jan 22 '13 at 18:24





@Takkat BTW nicely done in that other question. Good information.

– Luis Alvarado
Jan 22 '13 at 18:24




1




1





My wife just tested the Audacity method, and it worked perfectly! Recommended. Please, when people ask for advice it is because they are NOT experts. So don´t tell them to use command line tools when they can do the job with easy-to-understand graphical tools like Audacity. Telling new Linux users to open terminal and run command line tools will just scare them away from Ubuntu, with a feeling that Windows is simple, Linux is difficult. It is not a surprise that DOS is dead, but Windows is alive.

– user297240
Jun 23 '14 at 20:42





My wife just tested the Audacity method, and it worked perfectly! Recommended. Please, when people ask for advice it is because they are NOT experts. So don´t tell them to use command line tools when they can do the job with easy-to-understand graphical tools like Audacity. Telling new Linux users to open terminal and run command line tools will just scare them away from Ubuntu, with a feeling that Windows is simple, Linux is difficult. It is not a surprise that DOS is dead, but Windows is alive.

– user297240
Jun 23 '14 at 20:42













It's great your wife was able to figure out the graphical way, but did you miss the part where the person asking the question specifically wanted to achieve it via the terminal?

– RichardP
Apr 9 '17 at 5:53





It's great your wife was able to figure out the graphical way, but did you miss the part where the person asking the question specifically wanted to achieve it via the terminal?

– RichardP
Apr 9 '17 at 5:53










6 Answers
6






active

oldest

votes


















22



















Audacity



With Audacity we can easily batch process files to apply conversions or effects to many files in a list. To do so we first have to define a "Chain" containing the effects we want to apply.



This is done with "File --> Edit Chains...". In the now opening window press the Add button on the bottom left to insert a new chain (give it a sensible name):



enter image description here



Then choose the effect and it's parameters to insert to the chain (here shown for default values and the Normalize effect).




Important: we always need to also add the effect "Export MP3" (or any other export format) for saving the resulting conversion to disk.




When done leave this window with OK to open "File --> Apply Chain...". Select the Chain we have just created and load all files you need with "Apply to files...". Several files can be selected from the file chooser that opens.



enter image description here



Processed files will be saved in a new subdirectory "cleaned" in the original's path.




SoX



From version > 14.3 we can use the sox filter --norm for normalizing audio on the command line or for batch processing:



sox --norm infile outfile


MP3-support is added to Sox with libsox-fmt-all:



sudo apt install sox libsox-fmt-all





share|improve this answer






















  • 2





    Do these tools decode and re-encode?

    – qed
    Oct 29 '14 at 21:59











  • You can't normalize without re-encoding, at least the levels...

    – Takkat
    Oct 29 '14 at 22:03











  • For non-destructive live-normalizing using LADSPA and pulseaudio see askubuntu.com/questions/95716/…

    – Takkat
    Oct 29 '14 at 22:08











  • This does re-encode, so it reduces quality. See my answer if you want to preserve your file quality. Re-encoding is not necessary if your player supports volume tagging.

    – Wil
    May 16 at 6:21







  • 1





    to use sox in a batch you can use for f in *.mp3; do sox --norm "$f" /tmp/sox.mp3; mv -v /tmp/sox.mp3 "$f"; done

    – rubo77
    Sep 27 at 18:12


















30



















Take a look @ mp3gain which for me is even better than normalize-audio



mp3gain -r *.mp3


another useful version could be the -c which prevent to ask if you want to do the changes for many files:



mp3gain -c -r *.mp3


as said in the man page:



mp3gain does not just do peak normalization, as many normalizers do. Instead, it does some statistical analysis to determine how loud the file actually sounds to the human ear. Also, the changes
mp3gain makes are completely lossless. There is no quality lost in the change because the program adjusts the mp3 file directly, without decoding and re-encoding.



Note: That package was removed on purpose on ubuntu 15.04.



Debian proposes the python-rgain package as replacement (The advantage is that 'replaygain' supports several file formats, namely Ogg Vorbis , Flac, WavPack and MP3. Also, it allows you to view existing Replay Gain information in any of those file types). After installing it, run replaygain.



To install python-rgain from the terminal, run the command



sudo apt-get install python-rgain


Alternatively, get the .deb file for 14.04 (the latest) from here. Install as usual. After that, you need to run sudo apt-get -f install to correct some dependencies issues.






share|improve this answer






















  • 1





    Also, if you don't want to use the terminal, there is a GUI available for it named easymp3gain-gtk, which makes it very handy!

    – gilbertohasnofb
    Nov 12 '14 at 21:26











  • This is super useful. I was very impressed by the quality of normalization using MP3Gain's Windows GUI, so I was glad to find this answer when I needed a Linux command line solution. Would definitely recommend to others.

    – Alex P. Miller
    Feb 5 '15 at 18:05











  • Could you please add some information on how to install it? It doesn't come with Ubuntu by default, and I can't find the package.

    – Błażej Michalik
    May 3 '16 at 17:36












  • Thanks... installed python-rgain without any dependency errors on Ubuntu 16.04.

    – Bharat Mallapur
    Oct 13 '18 at 6:47











  • install with mkdir mp3gain; cd mp3gain; wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/mp3gain/1.5.2-r2-6/mp3gain_1.5.2-r2.orig.tar.gz; tar -xvzf mp3gain_1.5.2-r2.orig.tar.gz; make; sudo make install

    – rubo77
    Sep 27 at 19:21



















14



















I would use this project Normalize, it's a command-line tool for normalizing audio files. Looks to be exactly what you need. Can do batch processing and doesn't require resampling to intermediate formats.



It's in the package repos as normalize-audio, sudo apt-get install normalize-audio. This is a build maintained upstream by Debian so it should be in anything LTS or newer and is built with mp3 compatibility (tested). There is a good manpage man normalize-audio to explore the options but the commands defaults appear to work well. For batch processing (normalize volume across multiple files), normalize-audio -b *.mp3 or specify individual filenames instead of using wildcards.






share|improve this answer



























  • The OP wants instructions for doing this. Can you provide those?

    – Seth
    Jan 22 '13 at 18:13











  • @iSeth I was initially incorrect about the source only comment because I couldn't find it with apt-cache search. I've updated with details about the deb package.

    – sean_m
    Jan 23 '13 at 8:23












  • This seems a good alternative but can't find the correct encoder and get rid of "no encoder available". Tried with libsox-fmt-mp3, libavcodec-extra. -b *.mp3 do something with only one (random?) file.

    – Pablo A
    Mar 22 '17 at 19:04


















4



















replaygain



Faster and easy replaygain:




This package provides a Python package to calculate the Replay Gain values of audio files and normalize the volume of those files according to the values. Two basic scripts exploiting these capabilities are shipped as well.



Replay Gain is a proposed standard designed to solve the very problem of varying volumes across audio files.




Install: sudo apt install python-rgain.



replaygain --force *.mp3



  • -f, --force Recalculate Replay Gain even if the file already contains gain information.

Since only calculate/change replaygain value, is also faster: With an average PC (Intel i7-6500U, 8GB RAM) the rate was ~20 files/minute.



Reference




  • ReplayGain article at Wikipedia


  • python-rgain at Launchpad





share|improve this answer


































    3



















    For the sake of it, I'll throw my 2 cents in. I was looking for exactly the same thing (only for ogg files) and started a thread at Crunchbang Forum. You can view it here: Normalize-audio can't find mp3 decoder



    Basically my solution was the script in post #8. It works for mp3, flac, and ogg input files, possibly others but definitely not wav.



    Just create a file (name it whatever you want, I called mine db_adjust_mp3), chmod +x , and stick it in your ~/bin folder. It fills in any missing codec data as well. Example:



    Original file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains:



    vs.



    Normalized file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 192 kbps, 44.1 kHz, JntStereo



    I've modified the script to use normalize-mp3 here so you can use it if you want:



    #!/bin/bash

    find "$1" -iname "*.""$2" > $HOME/file_list

    cat $HOME/file_list | while read line; do
    # echo "$line"
    orig_gain="$(normalize-mp3 -n "$line" | cut -d 'd' -f1)"
    larger=$(echo "$orig_gain"'>'-12 | bc)
    if [[ larger ]]
    then
    gain_difference=$(echo "$orig_gain"*-1-12 | bc)
    else
    gain_difference=$(echo "$orig_gain"-12 | bc)
    fi
    echo "Gain Difference will be: $gain_difference""db"
    normalize-ogg --mp3 --bitrate "$3" -g "$gain_difference""db" -v "$line"
    done


    This script calculates the difference between the current db level and -12db, then applies a gain adjustment to put the gain at exactly -12db, which is what I've found works the best for me. It is recursive as well, which makes it great for doing entire music collections or files in many subfolders. If you wish to set a different db level, just change the both instances of the number "12" to whatever db level you would like to use. As I posted in my Crunchbang thread, usage is as follows:



    normalize-mp3 <directory> <file extenstion(with no leading dot)> <bitrate>


    However, when I used to keep my music library in mp3 format, I used to use mp3gain as well, just as Philippe suggested. The dead simplicity of it is great and I really liked it. The problem with normalize-audio though is that it does decode an re-endcode the files, so there is some sound degradation. But unless you're an audiophile and your mp3's are encoded at a high bitrate you shouldn't notice much difference.



    The thing I noticed with mp3gain though was that no matter what options I tried I couldn't get everything in my collection to be exactly the same db level, which is what I want so that I never have to adjust the volume from one track to the next. This script does exactly that. Sorry for being so long winded. Hope this helps.






    share|improve this answer
































      0



















      I liked Neil's answer the most, because it doesn't introduce correlation between audio files: just pick one gain level and adjust everything to it.



      However I had some problems parsing the output of normalize-ogg with some files I have.
      There is also one nasty issue with bc: it doesn't do real rounding, it only truncates.



      So eventually I gave up on shell scripting and moved to python.



      Note1: the exiftool part might be overkill but I wanted to be 100% sure that the original bitrate would be preserved.



      Note2: this will overwrite the originals, if you want to preserve them, use --backup in the last call to normalize-ogg. But I found more practical to keep a copy in a separate, safer, directory.



      Note3: this solution deals with ogg files, but it's trivial to adapt it to mp3, just replace the occurrences of "ogg" with "mp3".



      Here's my take at the problem.
      The latest version can be found here: regain.py



      #!/usr/bin/python3
      """
      Parallel normalize gains
      """
      '
      This program is free software: you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published by
      the Free Software Foundation, either version 3 of the License, or
      (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program. If not, see <http://www.gnu.org/licenses/>.
      '

      # Absolute value, in dB for the desired gain of each file
      TARGET_GAIN = -12

      #
      MAX_THREADS = 2

      from subprocess import Popen, PIPE
      from multiprocessing.dummy import Pool as ThreadPool
      from os import listdir
      import logging

      def initlogger(logfile="log.log", mainlevel=logging.DEBUG,
      filelevel=logging.DEBUG, consolelevel=logging.DEBUG):
      '''initlogger'''
      # create logger
      logger = logging.getLogger()
      logger.setLevel(mainlevel)
      # create file handler which logs even debug messages
      fh = logging.FileHandler(logfile)
      fh.setLevel(filelevel)
      # create console handler also logging at DEBUG level
      ch = logging.StreamHandler()
      ch.setLevel(consolelevel)
      # create formatter and add it to the handlers
      formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
      fh.setFormatter(formatter)
      ch.setFormatter(formatter)
      # add the handlers to the logger
      logger.addHandler(fh)
      logger.addHandler(ch)

      def logcommand(command=[]):
      '''logcommand'''
      if not isinstance(command, list):
      return "", "", -1
      logging.info("Command:n" + " ".join(command) + "n")
      proc = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
      output, err = proc.communicate()
      output = output.decode("utf-8")
      err = err.decode("utf-8")
      logging.info("Output:n" + output + "n")
      logging.info("Error:n" + err + "n")
      logging.info("Return Code:n" + str(proc.returncode) + "n")
      return output, err, proc.returncode

      def regain(target):
      '''regain'''
      logging.info("============================ Start File ============================")
      logging.warning(target["name"])
      logging.info("Extracting gain info.n")
      commandgetlevels = ['normalize-ogg', '-n', target["name"]]
      output, err, retcode = logcommand(commandgetlevels)

      level = output.split()[0]
      logging.debug("Level: " + level)
      if "dBFS" in level:
      level = level.split("dBFS")[0]
      level = level.replace(',', '.')
      level = int(round(float(level)))
      delta = target["gain"] - level
      logging.info("Required adjustment: " + str(delta) + "n")
      if delta is 0:
      logging.warning(target["name"] + " is already at the correct level")
      return 0

      logging.info("Extracting average bitrate.n")
      commandgetinfo = ['exiftool', target["name"]]
      output, err, retcode = logcommand(commandgetinfo)
      bitrate = '0'
      for line in output.split('n'):
      if 'Nominal Bitrate' in line:
      bitrate = line.split(':')[1].split()[0]
      break
      logging.info("Average bitrate is: " + str(bitrate) + "n")
      if bitrate is '0':
      logging.error("No valid bitrate found, aborting conversion.n")
      exit(-1)

      logging.info("Re-normalizing.n")
      commandrenormalize = ['normalize-ogg', '--ogg', '--bitrate', bitrate,
      '-g', str(delta) + 'db', target["name"]]
      output, err, retcode = logcommand(commandrenormalize)
      if retcode is not 0:
      log.error("Output:n" + output)
      log.error("err:n" + err)
      exit(retcode)

      return retcode

      # function to be mapped over
      def parallelregain(gain=TARGET_GAIN, threads=MAX_THREADS):
      '''parallelregain'''
      logging.info("Creating thread pool with " + str(threads) + " elements.n")
      pool = ThreadPool(threads)
      targets = []
      files_list = listdir(".")
      files_list.sort()
      counter = 0
      for filename in files_list:
      if filename.endswith("ogg"):
      target =
      "name":filename,
      "gain":gain,

      targets.append(target)
      counter = counter + 1
      pool.map(regain, targets)
      pool.close()
      pool.join()

      if __name__ == "__main__":
      initlogger(logfile="normalize.log", consolelevel=logging.WARNING)
      parallelregain()





      share|improve this answer




























        Your Answer








        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "89"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );














        draft saved

        draft discarded
















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f246242%2fhow-to-normalize-sound-in-mp3-files%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown


























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        22



















        Audacity



        With Audacity we can easily batch process files to apply conversions or effects to many files in a list. To do so we first have to define a "Chain" containing the effects we want to apply.



        This is done with "File --> Edit Chains...". In the now opening window press the Add button on the bottom left to insert a new chain (give it a sensible name):



        enter image description here



        Then choose the effect and it's parameters to insert to the chain (here shown for default values and the Normalize effect).




        Important: we always need to also add the effect "Export MP3" (or any other export format) for saving the resulting conversion to disk.




        When done leave this window with OK to open "File --> Apply Chain...". Select the Chain we have just created and load all files you need with "Apply to files...". Several files can be selected from the file chooser that opens.



        enter image description here



        Processed files will be saved in a new subdirectory "cleaned" in the original's path.




        SoX



        From version > 14.3 we can use the sox filter --norm for normalizing audio on the command line or for batch processing:



        sox --norm infile outfile


        MP3-support is added to Sox with libsox-fmt-all:



        sudo apt install sox libsox-fmt-all





        share|improve this answer






















        • 2





          Do these tools decode and re-encode?

          – qed
          Oct 29 '14 at 21:59











        • You can't normalize without re-encoding, at least the levels...

          – Takkat
          Oct 29 '14 at 22:03











        • For non-destructive live-normalizing using LADSPA and pulseaudio see askubuntu.com/questions/95716/…

          – Takkat
          Oct 29 '14 at 22:08











        • This does re-encode, so it reduces quality. See my answer if you want to preserve your file quality. Re-encoding is not necessary if your player supports volume tagging.

          – Wil
          May 16 at 6:21







        • 1





          to use sox in a batch you can use for f in *.mp3; do sox --norm "$f" /tmp/sox.mp3; mv -v /tmp/sox.mp3 "$f"; done

          – rubo77
          Sep 27 at 18:12















        22



















        Audacity



        With Audacity we can easily batch process files to apply conversions or effects to many files in a list. To do so we first have to define a "Chain" containing the effects we want to apply.



        This is done with "File --> Edit Chains...". In the now opening window press the Add button on the bottom left to insert a new chain (give it a sensible name):



        enter image description here



        Then choose the effect and it's parameters to insert to the chain (here shown for default values and the Normalize effect).




        Important: we always need to also add the effect "Export MP3" (or any other export format) for saving the resulting conversion to disk.




        When done leave this window with OK to open "File --> Apply Chain...". Select the Chain we have just created and load all files you need with "Apply to files...". Several files can be selected from the file chooser that opens.



        enter image description here



        Processed files will be saved in a new subdirectory "cleaned" in the original's path.




        SoX



        From version > 14.3 we can use the sox filter --norm for normalizing audio on the command line or for batch processing:



        sox --norm infile outfile


        MP3-support is added to Sox with libsox-fmt-all:



        sudo apt install sox libsox-fmt-all





        share|improve this answer






















        • 2





          Do these tools decode and re-encode?

          – qed
          Oct 29 '14 at 21:59











        • You can't normalize without re-encoding, at least the levels...

          – Takkat
          Oct 29 '14 at 22:03











        • For non-destructive live-normalizing using LADSPA and pulseaudio see askubuntu.com/questions/95716/…

          – Takkat
          Oct 29 '14 at 22:08











        • This does re-encode, so it reduces quality. See my answer if you want to preserve your file quality. Re-encoding is not necessary if your player supports volume tagging.

          – Wil
          May 16 at 6:21







        • 1





          to use sox in a batch you can use for f in *.mp3; do sox --norm "$f" /tmp/sox.mp3; mv -v /tmp/sox.mp3 "$f"; done

          – rubo77
          Sep 27 at 18:12













        22















        22











        22









        Audacity



        With Audacity we can easily batch process files to apply conversions or effects to many files in a list. To do so we first have to define a "Chain" containing the effects we want to apply.



        This is done with "File --> Edit Chains...". In the now opening window press the Add button on the bottom left to insert a new chain (give it a sensible name):



        enter image description here



        Then choose the effect and it's parameters to insert to the chain (here shown for default values and the Normalize effect).




        Important: we always need to also add the effect "Export MP3" (or any other export format) for saving the resulting conversion to disk.




        When done leave this window with OK to open "File --> Apply Chain...". Select the Chain we have just created and load all files you need with "Apply to files...". Several files can be selected from the file chooser that opens.



        enter image description here



        Processed files will be saved in a new subdirectory "cleaned" in the original's path.




        SoX



        From version > 14.3 we can use the sox filter --norm for normalizing audio on the command line or for batch processing:



        sox --norm infile outfile


        MP3-support is added to Sox with libsox-fmt-all:



        sudo apt install sox libsox-fmt-all





        share|improve this answer
















        Audacity



        With Audacity we can easily batch process files to apply conversions or effects to many files in a list. To do so we first have to define a "Chain" containing the effects we want to apply.



        This is done with "File --> Edit Chains...". In the now opening window press the Add button on the bottom left to insert a new chain (give it a sensible name):



        enter image description here



        Then choose the effect and it's parameters to insert to the chain (here shown for default values and the Normalize effect).




        Important: we always need to also add the effect "Export MP3" (or any other export format) for saving the resulting conversion to disk.




        When done leave this window with OK to open "File --> Apply Chain...". Select the Chain we have just created and load all files you need with "Apply to files...". Several files can be selected from the file chooser that opens.



        enter image description here



        Processed files will be saved in a new subdirectory "cleaned" in the original's path.




        SoX



        From version > 14.3 we can use the sox filter --norm for normalizing audio on the command line or for batch processing:



        sox --norm infile outfile


        MP3-support is added to Sox with libsox-fmt-all:



        sudo apt install sox libsox-fmt-all






        share|improve this answer















        share|improve this answer




        share|improve this answer








        edited Sep 27 at 18:08

























        answered Jan 22 '13 at 18:36









        TakkatTakkat

        119k40 gold badges263 silver badges386 bronze badges




        119k40 gold badges263 silver badges386 bronze badges










        • 2





          Do these tools decode and re-encode?

          – qed
          Oct 29 '14 at 21:59











        • You can't normalize without re-encoding, at least the levels...

          – Takkat
          Oct 29 '14 at 22:03











        • For non-destructive live-normalizing using LADSPA and pulseaudio see askubuntu.com/questions/95716/…

          – Takkat
          Oct 29 '14 at 22:08











        • This does re-encode, so it reduces quality. See my answer if you want to preserve your file quality. Re-encoding is not necessary if your player supports volume tagging.

          – Wil
          May 16 at 6:21







        • 1





          to use sox in a batch you can use for f in *.mp3; do sox --norm "$f" /tmp/sox.mp3; mv -v /tmp/sox.mp3 "$f"; done

          – rubo77
          Sep 27 at 18:12












        • 2





          Do these tools decode and re-encode?

          – qed
          Oct 29 '14 at 21:59











        • You can't normalize without re-encoding, at least the levels...

          – Takkat
          Oct 29 '14 at 22:03











        • For non-destructive live-normalizing using LADSPA and pulseaudio see askubuntu.com/questions/95716/…

          – Takkat
          Oct 29 '14 at 22:08











        • This does re-encode, so it reduces quality. See my answer if you want to preserve your file quality. Re-encoding is not necessary if your player supports volume tagging.

          – Wil
          May 16 at 6:21







        • 1





          to use sox in a batch you can use for f in *.mp3; do sox --norm "$f" /tmp/sox.mp3; mv -v /tmp/sox.mp3 "$f"; done

          – rubo77
          Sep 27 at 18:12







        2




        2





        Do these tools decode and re-encode?

        – qed
        Oct 29 '14 at 21:59





        Do these tools decode and re-encode?

        – qed
        Oct 29 '14 at 21:59













        You can't normalize without re-encoding, at least the levels...

        – Takkat
        Oct 29 '14 at 22:03





        You can't normalize without re-encoding, at least the levels...

        – Takkat
        Oct 29 '14 at 22:03













        For non-destructive live-normalizing using LADSPA and pulseaudio see askubuntu.com/questions/95716/…

        – Takkat
        Oct 29 '14 at 22:08





        For non-destructive live-normalizing using LADSPA and pulseaudio see askubuntu.com/questions/95716/…

        – Takkat
        Oct 29 '14 at 22:08













        This does re-encode, so it reduces quality. See my answer if you want to preserve your file quality. Re-encoding is not necessary if your player supports volume tagging.

        – Wil
        May 16 at 6:21






        This does re-encode, so it reduces quality. See my answer if you want to preserve your file quality. Re-encoding is not necessary if your player supports volume tagging.

        – Wil
        May 16 at 6:21





        1




        1





        to use sox in a batch you can use for f in *.mp3; do sox --norm "$f" /tmp/sox.mp3; mv -v /tmp/sox.mp3 "$f"; done

        – rubo77
        Sep 27 at 18:12





        to use sox in a batch you can use for f in *.mp3; do sox --norm "$f" /tmp/sox.mp3; mv -v /tmp/sox.mp3 "$f"; done

        – rubo77
        Sep 27 at 18:12













        30



















        Take a look @ mp3gain which for me is even better than normalize-audio



        mp3gain -r *.mp3


        another useful version could be the -c which prevent to ask if you want to do the changes for many files:



        mp3gain -c -r *.mp3


        as said in the man page:



        mp3gain does not just do peak normalization, as many normalizers do. Instead, it does some statistical analysis to determine how loud the file actually sounds to the human ear. Also, the changes
        mp3gain makes are completely lossless. There is no quality lost in the change because the program adjusts the mp3 file directly, without decoding and re-encoding.



        Note: That package was removed on purpose on ubuntu 15.04.



        Debian proposes the python-rgain package as replacement (The advantage is that 'replaygain' supports several file formats, namely Ogg Vorbis , Flac, WavPack and MP3. Also, it allows you to view existing Replay Gain information in any of those file types). After installing it, run replaygain.



        To install python-rgain from the terminal, run the command



        sudo apt-get install python-rgain


        Alternatively, get the .deb file for 14.04 (the latest) from here. Install as usual. After that, you need to run sudo apt-get -f install to correct some dependencies issues.






        share|improve this answer






















        • 1





          Also, if you don't want to use the terminal, there is a GUI available for it named easymp3gain-gtk, which makes it very handy!

          – gilbertohasnofb
          Nov 12 '14 at 21:26











        • This is super useful. I was very impressed by the quality of normalization using MP3Gain's Windows GUI, so I was glad to find this answer when I needed a Linux command line solution. Would definitely recommend to others.

          – Alex P. Miller
          Feb 5 '15 at 18:05











        • Could you please add some information on how to install it? It doesn't come with Ubuntu by default, and I can't find the package.

          – Błażej Michalik
          May 3 '16 at 17:36












        • Thanks... installed python-rgain without any dependency errors on Ubuntu 16.04.

          – Bharat Mallapur
          Oct 13 '18 at 6:47











        • install with mkdir mp3gain; cd mp3gain; wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/mp3gain/1.5.2-r2-6/mp3gain_1.5.2-r2.orig.tar.gz; tar -xvzf mp3gain_1.5.2-r2.orig.tar.gz; make; sudo make install

          – rubo77
          Sep 27 at 19:21
















        30



















        Take a look @ mp3gain which for me is even better than normalize-audio



        mp3gain -r *.mp3


        another useful version could be the -c which prevent to ask if you want to do the changes for many files:



        mp3gain -c -r *.mp3


        as said in the man page:



        mp3gain does not just do peak normalization, as many normalizers do. Instead, it does some statistical analysis to determine how loud the file actually sounds to the human ear. Also, the changes
        mp3gain makes are completely lossless. There is no quality lost in the change because the program adjusts the mp3 file directly, without decoding and re-encoding.



        Note: That package was removed on purpose on ubuntu 15.04.



        Debian proposes the python-rgain package as replacement (The advantage is that 'replaygain' supports several file formats, namely Ogg Vorbis , Flac, WavPack and MP3. Also, it allows you to view existing Replay Gain information in any of those file types). After installing it, run replaygain.



        To install python-rgain from the terminal, run the command



        sudo apt-get install python-rgain


        Alternatively, get the .deb file for 14.04 (the latest) from here. Install as usual. After that, you need to run sudo apt-get -f install to correct some dependencies issues.






        share|improve this answer






















        • 1





          Also, if you don't want to use the terminal, there is a GUI available for it named easymp3gain-gtk, which makes it very handy!

          – gilbertohasnofb
          Nov 12 '14 at 21:26











        • This is super useful. I was very impressed by the quality of normalization using MP3Gain's Windows GUI, so I was glad to find this answer when I needed a Linux command line solution. Would definitely recommend to others.

          – Alex P. Miller
          Feb 5 '15 at 18:05











        • Could you please add some information on how to install it? It doesn't come with Ubuntu by default, and I can't find the package.

          – Błażej Michalik
          May 3 '16 at 17:36












        • Thanks... installed python-rgain without any dependency errors on Ubuntu 16.04.

          – Bharat Mallapur
          Oct 13 '18 at 6:47











        • install with mkdir mp3gain; cd mp3gain; wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/mp3gain/1.5.2-r2-6/mp3gain_1.5.2-r2.orig.tar.gz; tar -xvzf mp3gain_1.5.2-r2.orig.tar.gz; make; sudo make install

          – rubo77
          Sep 27 at 19:21














        30















        30











        30









        Take a look @ mp3gain which for me is even better than normalize-audio



        mp3gain -r *.mp3


        another useful version could be the -c which prevent to ask if you want to do the changes for many files:



        mp3gain -c -r *.mp3


        as said in the man page:



        mp3gain does not just do peak normalization, as many normalizers do. Instead, it does some statistical analysis to determine how loud the file actually sounds to the human ear. Also, the changes
        mp3gain makes are completely lossless. There is no quality lost in the change because the program adjusts the mp3 file directly, without decoding and re-encoding.



        Note: That package was removed on purpose on ubuntu 15.04.



        Debian proposes the python-rgain package as replacement (The advantage is that 'replaygain' supports several file formats, namely Ogg Vorbis , Flac, WavPack and MP3. Also, it allows you to view existing Replay Gain information in any of those file types). After installing it, run replaygain.



        To install python-rgain from the terminal, run the command



        sudo apt-get install python-rgain


        Alternatively, get the .deb file for 14.04 (the latest) from here. Install as usual. After that, you need to run sudo apt-get -f install to correct some dependencies issues.






        share|improve this answer
















        Take a look @ mp3gain which for me is even better than normalize-audio



        mp3gain -r *.mp3


        another useful version could be the -c which prevent to ask if you want to do the changes for many files:



        mp3gain -c -r *.mp3


        as said in the man page:



        mp3gain does not just do peak normalization, as many normalizers do. Instead, it does some statistical analysis to determine how loud the file actually sounds to the human ear. Also, the changes
        mp3gain makes are completely lossless. There is no quality lost in the change because the program adjusts the mp3 file directly, without decoding and re-encoding.



        Note: That package was removed on purpose on ubuntu 15.04.



        Debian proposes the python-rgain package as replacement (The advantage is that 'replaygain' supports several file formats, namely Ogg Vorbis , Flac, WavPack and MP3. Also, it allows you to view existing Replay Gain information in any of those file types). After installing it, run replaygain.



        To install python-rgain from the terminal, run the command



        sudo apt-get install python-rgain


        Alternatively, get the .deb file for 14.04 (the latest) from here. Install as usual. After that, you need to run sudo apt-get -f install to correct some dependencies issues.







        share|improve this answer















        share|improve this answer




        share|improve this answer








        edited Oct 13 '18 at 8:21









        Bharat Mallapur

        1355 bronze badges




        1355 bronze badges










        answered Sep 27 '13 at 12:02









        Philippe GachoudPhilippe Gachoud

        3,9471 gold badge28 silver badges42 bronze badges




        3,9471 gold badge28 silver badges42 bronze badges










        • 1





          Also, if you don't want to use the terminal, there is a GUI available for it named easymp3gain-gtk, which makes it very handy!

          – gilbertohasnofb
          Nov 12 '14 at 21:26











        • This is super useful. I was very impressed by the quality of normalization using MP3Gain's Windows GUI, so I was glad to find this answer when I needed a Linux command line solution. Would definitely recommend to others.

          – Alex P. Miller
          Feb 5 '15 at 18:05











        • Could you please add some information on how to install it? It doesn't come with Ubuntu by default, and I can't find the package.

          – Błażej Michalik
          May 3 '16 at 17:36












        • Thanks... installed python-rgain without any dependency errors on Ubuntu 16.04.

          – Bharat Mallapur
          Oct 13 '18 at 6:47











        • install with mkdir mp3gain; cd mp3gain; wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/mp3gain/1.5.2-r2-6/mp3gain_1.5.2-r2.orig.tar.gz; tar -xvzf mp3gain_1.5.2-r2.orig.tar.gz; make; sudo make install

          – rubo77
          Sep 27 at 19:21













        • 1





          Also, if you don't want to use the terminal, there is a GUI available for it named easymp3gain-gtk, which makes it very handy!

          – gilbertohasnofb
          Nov 12 '14 at 21:26











        • This is super useful. I was very impressed by the quality of normalization using MP3Gain's Windows GUI, so I was glad to find this answer when I needed a Linux command line solution. Would definitely recommend to others.

          – Alex P. Miller
          Feb 5 '15 at 18:05











        • Could you please add some information on how to install it? It doesn't come with Ubuntu by default, and I can't find the package.

          – Błażej Michalik
          May 3 '16 at 17:36












        • Thanks... installed python-rgain without any dependency errors on Ubuntu 16.04.

          – Bharat Mallapur
          Oct 13 '18 at 6:47











        • install with mkdir mp3gain; cd mp3gain; wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/mp3gain/1.5.2-r2-6/mp3gain_1.5.2-r2.orig.tar.gz; tar -xvzf mp3gain_1.5.2-r2.orig.tar.gz; make; sudo make install

          – rubo77
          Sep 27 at 19:21








        1




        1





        Also, if you don't want to use the terminal, there is a GUI available for it named easymp3gain-gtk, which makes it very handy!

        – gilbertohasnofb
        Nov 12 '14 at 21:26





        Also, if you don't want to use the terminal, there is a GUI available for it named easymp3gain-gtk, which makes it very handy!

        – gilbertohasnofb
        Nov 12 '14 at 21:26













        This is super useful. I was very impressed by the quality of normalization using MP3Gain's Windows GUI, so I was glad to find this answer when I needed a Linux command line solution. Would definitely recommend to others.

        – Alex P. Miller
        Feb 5 '15 at 18:05





        This is super useful. I was very impressed by the quality of normalization using MP3Gain's Windows GUI, so I was glad to find this answer when I needed a Linux command line solution. Would definitely recommend to others.

        – Alex P. Miller
        Feb 5 '15 at 18:05













        Could you please add some information on how to install it? It doesn't come with Ubuntu by default, and I can't find the package.

        – Błażej Michalik
        May 3 '16 at 17:36






        Could you please add some information on how to install it? It doesn't come with Ubuntu by default, and I can't find the package.

        – Błażej Michalik
        May 3 '16 at 17:36














        Thanks... installed python-rgain without any dependency errors on Ubuntu 16.04.

        – Bharat Mallapur
        Oct 13 '18 at 6:47





        Thanks... installed python-rgain without any dependency errors on Ubuntu 16.04.

        – Bharat Mallapur
        Oct 13 '18 at 6:47













        install with mkdir mp3gain; cd mp3gain; wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/mp3gain/1.5.2-r2-6/mp3gain_1.5.2-r2.orig.tar.gz; tar -xvzf mp3gain_1.5.2-r2.orig.tar.gz; make; sudo make install

        – rubo77
        Sep 27 at 19:21






        install with mkdir mp3gain; cd mp3gain; wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/mp3gain/1.5.2-r2-6/mp3gain_1.5.2-r2.orig.tar.gz; tar -xvzf mp3gain_1.5.2-r2.orig.tar.gz; make; sudo make install

        – rubo77
        Sep 27 at 19:21












        14



















        I would use this project Normalize, it's a command-line tool for normalizing audio files. Looks to be exactly what you need. Can do batch processing and doesn't require resampling to intermediate formats.



        It's in the package repos as normalize-audio, sudo apt-get install normalize-audio. This is a build maintained upstream by Debian so it should be in anything LTS or newer and is built with mp3 compatibility (tested). There is a good manpage man normalize-audio to explore the options but the commands defaults appear to work well. For batch processing (normalize volume across multiple files), normalize-audio -b *.mp3 or specify individual filenames instead of using wildcards.






        share|improve this answer



























        • The OP wants instructions for doing this. Can you provide those?

          – Seth
          Jan 22 '13 at 18:13











        • @iSeth I was initially incorrect about the source only comment because I couldn't find it with apt-cache search. I've updated with details about the deb package.

          – sean_m
          Jan 23 '13 at 8:23












        • This seems a good alternative but can't find the correct encoder and get rid of "no encoder available". Tried with libsox-fmt-mp3, libavcodec-extra. -b *.mp3 do something with only one (random?) file.

          – Pablo A
          Mar 22 '17 at 19:04















        14



















        I would use this project Normalize, it's a command-line tool for normalizing audio files. Looks to be exactly what you need. Can do batch processing and doesn't require resampling to intermediate formats.



        It's in the package repos as normalize-audio, sudo apt-get install normalize-audio. This is a build maintained upstream by Debian so it should be in anything LTS or newer and is built with mp3 compatibility (tested). There is a good manpage man normalize-audio to explore the options but the commands defaults appear to work well. For batch processing (normalize volume across multiple files), normalize-audio -b *.mp3 or specify individual filenames instead of using wildcards.






        share|improve this answer



























        • The OP wants instructions for doing this. Can you provide those?

          – Seth
          Jan 22 '13 at 18:13











        • @iSeth I was initially incorrect about the source only comment because I couldn't find it with apt-cache search. I've updated with details about the deb package.

          – sean_m
          Jan 23 '13 at 8:23












        • This seems a good alternative but can't find the correct encoder and get rid of "no encoder available". Tried with libsox-fmt-mp3, libavcodec-extra. -b *.mp3 do something with only one (random?) file.

          – Pablo A
          Mar 22 '17 at 19:04













        14















        14











        14









        I would use this project Normalize, it's a command-line tool for normalizing audio files. Looks to be exactly what you need. Can do batch processing and doesn't require resampling to intermediate formats.



        It's in the package repos as normalize-audio, sudo apt-get install normalize-audio. This is a build maintained upstream by Debian so it should be in anything LTS or newer and is built with mp3 compatibility (tested). There is a good manpage man normalize-audio to explore the options but the commands defaults appear to work well. For batch processing (normalize volume across multiple files), normalize-audio -b *.mp3 or specify individual filenames instead of using wildcards.






        share|improve this answer
















        I would use this project Normalize, it's a command-line tool for normalizing audio files. Looks to be exactly what you need. Can do batch processing and doesn't require resampling to intermediate formats.



        It's in the package repos as normalize-audio, sudo apt-get install normalize-audio. This is a build maintained upstream by Debian so it should be in anything LTS or newer and is built with mp3 compatibility (tested). There is a good manpage man normalize-audio to explore the options but the commands defaults appear to work well. For batch processing (normalize volume across multiple files), normalize-audio -b *.mp3 or specify individual filenames instead of using wildcards.







        share|improve this answer















        share|improve this answer




        share|improve this answer








        edited Jan 22 '13 at 18:32

























        answered Jan 22 '13 at 18:09









        sean_msean_m

        3111 silver badge6 bronze badges




        3111 silver badge6 bronze badges















        • The OP wants instructions for doing this. Can you provide those?

          – Seth
          Jan 22 '13 at 18:13











        • @iSeth I was initially incorrect about the source only comment because I couldn't find it with apt-cache search. I've updated with details about the deb package.

          – sean_m
          Jan 23 '13 at 8:23












        • This seems a good alternative but can't find the correct encoder and get rid of "no encoder available". Tried with libsox-fmt-mp3, libavcodec-extra. -b *.mp3 do something with only one (random?) file.

          – Pablo A
          Mar 22 '17 at 19:04

















        • The OP wants instructions for doing this. Can you provide those?

          – Seth
          Jan 22 '13 at 18:13











        • @iSeth I was initially incorrect about the source only comment because I couldn't find it with apt-cache search. I've updated with details about the deb package.

          – sean_m
          Jan 23 '13 at 8:23












        • This seems a good alternative but can't find the correct encoder and get rid of "no encoder available". Tried with libsox-fmt-mp3, libavcodec-extra. -b *.mp3 do something with only one (random?) file.

          – Pablo A
          Mar 22 '17 at 19:04
















        The OP wants instructions for doing this. Can you provide those?

        – Seth
        Jan 22 '13 at 18:13





        The OP wants instructions for doing this. Can you provide those?

        – Seth
        Jan 22 '13 at 18:13













        @iSeth I was initially incorrect about the source only comment because I couldn't find it with apt-cache search. I've updated with details about the deb package.

        – sean_m
        Jan 23 '13 at 8:23






        @iSeth I was initially incorrect about the source only comment because I couldn't find it with apt-cache search. I've updated with details about the deb package.

        – sean_m
        Jan 23 '13 at 8:23














        This seems a good alternative but can't find the correct encoder and get rid of "no encoder available". Tried with libsox-fmt-mp3, libavcodec-extra. -b *.mp3 do something with only one (random?) file.

        – Pablo A
        Mar 22 '17 at 19:04





        This seems a good alternative but can't find the correct encoder and get rid of "no encoder available". Tried with libsox-fmt-mp3, libavcodec-extra. -b *.mp3 do something with only one (random?) file.

        – Pablo A
        Mar 22 '17 at 19:04











        4



















        replaygain



        Faster and easy replaygain:




        This package provides a Python package to calculate the Replay Gain values of audio files and normalize the volume of those files according to the values. Two basic scripts exploiting these capabilities are shipped as well.



        Replay Gain is a proposed standard designed to solve the very problem of varying volumes across audio files.




        Install: sudo apt install python-rgain.



        replaygain --force *.mp3



        • -f, --force Recalculate Replay Gain even if the file already contains gain information.

        Since only calculate/change replaygain value, is also faster: With an average PC (Intel i7-6500U, 8GB RAM) the rate was ~20 files/minute.



        Reference




        • ReplayGain article at Wikipedia


        • python-rgain at Launchpad





        share|improve this answer































          4



















          replaygain



          Faster and easy replaygain:




          This package provides a Python package to calculate the Replay Gain values of audio files and normalize the volume of those files according to the values. Two basic scripts exploiting these capabilities are shipped as well.



          Replay Gain is a proposed standard designed to solve the very problem of varying volumes across audio files.




          Install: sudo apt install python-rgain.



          replaygain --force *.mp3



          • -f, --force Recalculate Replay Gain even if the file already contains gain information.

          Since only calculate/change replaygain value, is also faster: With an average PC (Intel i7-6500U, 8GB RAM) the rate was ~20 files/minute.



          Reference




          • ReplayGain article at Wikipedia


          • python-rgain at Launchpad





          share|improve this answer





























            4















            4











            4









            replaygain



            Faster and easy replaygain:




            This package provides a Python package to calculate the Replay Gain values of audio files and normalize the volume of those files according to the values. Two basic scripts exploiting these capabilities are shipped as well.



            Replay Gain is a proposed standard designed to solve the very problem of varying volumes across audio files.




            Install: sudo apt install python-rgain.



            replaygain --force *.mp3



            • -f, --force Recalculate Replay Gain even if the file already contains gain information.

            Since only calculate/change replaygain value, is also faster: With an average PC (Intel i7-6500U, 8GB RAM) the rate was ~20 files/minute.



            Reference




            • ReplayGain article at Wikipedia


            • python-rgain at Launchpad





            share|improve this answer
















            replaygain



            Faster and easy replaygain:




            This package provides a Python package to calculate the Replay Gain values of audio files and normalize the volume of those files according to the values. Two basic scripts exploiting these capabilities are shipped as well.



            Replay Gain is a proposed standard designed to solve the very problem of varying volumes across audio files.




            Install: sudo apt install python-rgain.



            replaygain --force *.mp3



            • -f, --force Recalculate Replay Gain even if the file already contains gain information.

            Since only calculate/change replaygain value, is also faster: With an average PC (Intel i7-6500U, 8GB RAM) the rate was ~20 files/minute.



            Reference




            • ReplayGain article at Wikipedia


            • python-rgain at Launchpad






            share|improve this answer















            share|improve this answer




            share|improve this answer








            edited May 16 at 21:49

























            answered Mar 22 '17 at 20:01









            Pablo APablo A

            4,6433 gold badges25 silver badges50 bronze badges




            4,6433 gold badges25 silver badges50 bronze badges
























                3



















                For the sake of it, I'll throw my 2 cents in. I was looking for exactly the same thing (only for ogg files) and started a thread at Crunchbang Forum. You can view it here: Normalize-audio can't find mp3 decoder



                Basically my solution was the script in post #8. It works for mp3, flac, and ogg input files, possibly others but definitely not wav.



                Just create a file (name it whatever you want, I called mine db_adjust_mp3), chmod +x , and stick it in your ~/bin folder. It fills in any missing codec data as well. Example:



                Original file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains:



                vs.



                Normalized file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 192 kbps, 44.1 kHz, JntStereo



                I've modified the script to use normalize-mp3 here so you can use it if you want:



                #!/bin/bash

                find "$1" -iname "*.""$2" > $HOME/file_list

                cat $HOME/file_list | while read line; do
                # echo "$line"
                orig_gain="$(normalize-mp3 -n "$line" | cut -d 'd' -f1)"
                larger=$(echo "$orig_gain"'>'-12 | bc)
                if [[ larger ]]
                then
                gain_difference=$(echo "$orig_gain"*-1-12 | bc)
                else
                gain_difference=$(echo "$orig_gain"-12 | bc)
                fi
                echo "Gain Difference will be: $gain_difference""db"
                normalize-ogg --mp3 --bitrate "$3" -g "$gain_difference""db" -v "$line"
                done


                This script calculates the difference between the current db level and -12db, then applies a gain adjustment to put the gain at exactly -12db, which is what I've found works the best for me. It is recursive as well, which makes it great for doing entire music collections or files in many subfolders. If you wish to set a different db level, just change the both instances of the number "12" to whatever db level you would like to use. As I posted in my Crunchbang thread, usage is as follows:



                normalize-mp3 <directory> <file extenstion(with no leading dot)> <bitrate>


                However, when I used to keep my music library in mp3 format, I used to use mp3gain as well, just as Philippe suggested. The dead simplicity of it is great and I really liked it. The problem with normalize-audio though is that it does decode an re-endcode the files, so there is some sound degradation. But unless you're an audiophile and your mp3's are encoded at a high bitrate you shouldn't notice much difference.



                The thing I noticed with mp3gain though was that no matter what options I tried I couldn't get everything in my collection to be exactly the same db level, which is what I want so that I never have to adjust the volume from one track to the next. This script does exactly that. Sorry for being so long winded. Hope this helps.






                share|improve this answer





























                  3



















                  For the sake of it, I'll throw my 2 cents in. I was looking for exactly the same thing (only for ogg files) and started a thread at Crunchbang Forum. You can view it here: Normalize-audio can't find mp3 decoder



                  Basically my solution was the script in post #8. It works for mp3, flac, and ogg input files, possibly others but definitely not wav.



                  Just create a file (name it whatever you want, I called mine db_adjust_mp3), chmod +x , and stick it in your ~/bin folder. It fills in any missing codec data as well. Example:



                  Original file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains:



                  vs.



                  Normalized file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 192 kbps, 44.1 kHz, JntStereo



                  I've modified the script to use normalize-mp3 here so you can use it if you want:



                  #!/bin/bash

                  find "$1" -iname "*.""$2" > $HOME/file_list

                  cat $HOME/file_list | while read line; do
                  # echo "$line"
                  orig_gain="$(normalize-mp3 -n "$line" | cut -d 'd' -f1)"
                  larger=$(echo "$orig_gain"'>'-12 | bc)
                  if [[ larger ]]
                  then
                  gain_difference=$(echo "$orig_gain"*-1-12 | bc)
                  else
                  gain_difference=$(echo "$orig_gain"-12 | bc)
                  fi
                  echo "Gain Difference will be: $gain_difference""db"
                  normalize-ogg --mp3 --bitrate "$3" -g "$gain_difference""db" -v "$line"
                  done


                  This script calculates the difference between the current db level and -12db, then applies a gain adjustment to put the gain at exactly -12db, which is what I've found works the best for me. It is recursive as well, which makes it great for doing entire music collections or files in many subfolders. If you wish to set a different db level, just change the both instances of the number "12" to whatever db level you would like to use. As I posted in my Crunchbang thread, usage is as follows:



                  normalize-mp3 <directory> <file extenstion(with no leading dot)> <bitrate>


                  However, when I used to keep my music library in mp3 format, I used to use mp3gain as well, just as Philippe suggested. The dead simplicity of it is great and I really liked it. The problem with normalize-audio though is that it does decode an re-endcode the files, so there is some sound degradation. But unless you're an audiophile and your mp3's are encoded at a high bitrate you shouldn't notice much difference.



                  The thing I noticed with mp3gain though was that no matter what options I tried I couldn't get everything in my collection to be exactly the same db level, which is what I want so that I never have to adjust the volume from one track to the next. This script does exactly that. Sorry for being so long winded. Hope this helps.






                  share|improve this answer



























                    3















                    3











                    3









                    For the sake of it, I'll throw my 2 cents in. I was looking for exactly the same thing (only for ogg files) and started a thread at Crunchbang Forum. You can view it here: Normalize-audio can't find mp3 decoder



                    Basically my solution was the script in post #8. It works for mp3, flac, and ogg input files, possibly others but definitely not wav.



                    Just create a file (name it whatever you want, I called mine db_adjust_mp3), chmod +x , and stick it in your ~/bin folder. It fills in any missing codec data as well. Example:



                    Original file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains:



                    vs.



                    Normalized file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 192 kbps, 44.1 kHz, JntStereo



                    I've modified the script to use normalize-mp3 here so you can use it if you want:



                    #!/bin/bash

                    find "$1" -iname "*.""$2" > $HOME/file_list

                    cat $HOME/file_list | while read line; do
                    # echo "$line"
                    orig_gain="$(normalize-mp3 -n "$line" | cut -d 'd' -f1)"
                    larger=$(echo "$orig_gain"'>'-12 | bc)
                    if [[ larger ]]
                    then
                    gain_difference=$(echo "$orig_gain"*-1-12 | bc)
                    else
                    gain_difference=$(echo "$orig_gain"-12 | bc)
                    fi
                    echo "Gain Difference will be: $gain_difference""db"
                    normalize-ogg --mp3 --bitrate "$3" -g "$gain_difference""db" -v "$line"
                    done


                    This script calculates the difference between the current db level and -12db, then applies a gain adjustment to put the gain at exactly -12db, which is what I've found works the best for me. It is recursive as well, which makes it great for doing entire music collections or files in many subfolders. If you wish to set a different db level, just change the both instances of the number "12" to whatever db level you would like to use. As I posted in my Crunchbang thread, usage is as follows:



                    normalize-mp3 <directory> <file extenstion(with no leading dot)> <bitrate>


                    However, when I used to keep my music library in mp3 format, I used to use mp3gain as well, just as Philippe suggested. The dead simplicity of it is great and I really liked it. The problem with normalize-audio though is that it does decode an re-endcode the files, so there is some sound degradation. But unless you're an audiophile and your mp3's are encoded at a high bitrate you shouldn't notice much difference.



                    The thing I noticed with mp3gain though was that no matter what options I tried I couldn't get everything in my collection to be exactly the same db level, which is what I want so that I never have to adjust the volume from one track to the next. This script does exactly that. Sorry for being so long winded. Hope this helps.






                    share|improve this answer














                    For the sake of it, I'll throw my 2 cents in. I was looking for exactly the same thing (only for ogg files) and started a thread at Crunchbang Forum. You can view it here: Normalize-audio can't find mp3 decoder



                    Basically my solution was the script in post #8. It works for mp3, flac, and ogg input files, possibly others but definitely not wav.



                    Just create a file (name it whatever you want, I called mine db_adjust_mp3), chmod +x , and stick it in your ~/bin folder. It fills in any missing codec data as well. Example:



                    Original file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains:



                    vs.



                    Normalized file: 16._This_Protector.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 192 kbps, 44.1 kHz, JntStereo



                    I've modified the script to use normalize-mp3 here so you can use it if you want:



                    #!/bin/bash

                    find "$1" -iname "*.""$2" > $HOME/file_list

                    cat $HOME/file_list | while read line; do
                    # echo "$line"
                    orig_gain="$(normalize-mp3 -n "$line" | cut -d 'd' -f1)"
                    larger=$(echo "$orig_gain"'>'-12 | bc)
                    if [[ larger ]]
                    then
                    gain_difference=$(echo "$orig_gain"*-1-12 | bc)
                    else
                    gain_difference=$(echo "$orig_gain"-12 | bc)
                    fi
                    echo "Gain Difference will be: $gain_difference""db"
                    normalize-ogg --mp3 --bitrate "$3" -g "$gain_difference""db" -v "$line"
                    done


                    This script calculates the difference between the current db level and -12db, then applies a gain adjustment to put the gain at exactly -12db, which is what I've found works the best for me. It is recursive as well, which makes it great for doing entire music collections or files in many subfolders. If you wish to set a different db level, just change the both instances of the number "12" to whatever db level you would like to use. As I posted in my Crunchbang thread, usage is as follows:



                    normalize-mp3 <directory> <file extenstion(with no leading dot)> <bitrate>


                    However, when I used to keep my music library in mp3 format, I used to use mp3gain as well, just as Philippe suggested. The dead simplicity of it is great and I really liked it. The problem with normalize-audio though is that it does decode an re-endcode the files, so there is some sound degradation. But unless you're an audiophile and your mp3's are encoded at a high bitrate you shouldn't notice much difference.



                    The thing I noticed with mp3gain though was that no matter what options I tried I couldn't get everything in my collection to be exactly the same db level, which is what I want so that I never have to adjust the volume from one track to the next. This script does exactly that. Sorry for being so long winded. Hope this helps.







                    share|improve this answer













                    share|improve this answer




                    share|improve this answer










                    answered Oct 20 '13 at 11:18









                    NeilNeil

                    312 bronze badges




                    312 bronze badges
























                        0



















                        I liked Neil's answer the most, because it doesn't introduce correlation between audio files: just pick one gain level and adjust everything to it.



                        However I had some problems parsing the output of normalize-ogg with some files I have.
                        There is also one nasty issue with bc: it doesn't do real rounding, it only truncates.



                        So eventually I gave up on shell scripting and moved to python.



                        Note1: the exiftool part might be overkill but I wanted to be 100% sure that the original bitrate would be preserved.



                        Note2: this will overwrite the originals, if you want to preserve them, use --backup in the last call to normalize-ogg. But I found more practical to keep a copy in a separate, safer, directory.



                        Note3: this solution deals with ogg files, but it's trivial to adapt it to mp3, just replace the occurrences of "ogg" with "mp3".



                        Here's my take at the problem.
                        The latest version can be found here: regain.py



                        #!/usr/bin/python3
                        """
                        Parallel normalize gains
                        """
                        '
                        This program is free software: you can redistribute it and/or modify
                        it under the terms of the GNU General Public License as published by
                        the Free Software Foundation, either version 3 of the License, or
                        (at your option) any later version.

                        This program is distributed in the hope that it will be useful,
                        but WITHOUT ANY WARRANTY; without even the implied warranty of
                        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
                        GNU General Public License for more details.

                        You should have received a copy of the GNU General Public License
                        along with this program. If not, see <http://www.gnu.org/licenses/>.
                        '

                        # Absolute value, in dB for the desired gain of each file
                        TARGET_GAIN = -12

                        #
                        MAX_THREADS = 2

                        from subprocess import Popen, PIPE
                        from multiprocessing.dummy import Pool as ThreadPool
                        from os import listdir
                        import logging

                        def initlogger(logfile="log.log", mainlevel=logging.DEBUG,
                        filelevel=logging.DEBUG, consolelevel=logging.DEBUG):
                        '''initlogger'''
                        # create logger
                        logger = logging.getLogger()
                        logger.setLevel(mainlevel)
                        # create file handler which logs even debug messages
                        fh = logging.FileHandler(logfile)
                        fh.setLevel(filelevel)
                        # create console handler also logging at DEBUG level
                        ch = logging.StreamHandler()
                        ch.setLevel(consolelevel)
                        # create formatter and add it to the handlers
                        formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
                        fh.setFormatter(formatter)
                        ch.setFormatter(formatter)
                        # add the handlers to the logger
                        logger.addHandler(fh)
                        logger.addHandler(ch)

                        def logcommand(command=[]):
                        '''logcommand'''
                        if not isinstance(command, list):
                        return "", "", -1
                        logging.info("Command:n" + " ".join(command) + "n")
                        proc = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                        output, err = proc.communicate()
                        output = output.decode("utf-8")
                        err = err.decode("utf-8")
                        logging.info("Output:n" + output + "n")
                        logging.info("Error:n" + err + "n")
                        logging.info("Return Code:n" + str(proc.returncode) + "n")
                        return output, err, proc.returncode

                        def regain(target):
                        '''regain'''
                        logging.info("============================ Start File ============================")
                        logging.warning(target["name"])
                        logging.info("Extracting gain info.n")
                        commandgetlevels = ['normalize-ogg', '-n', target["name"]]
                        output, err, retcode = logcommand(commandgetlevels)

                        level = output.split()[0]
                        logging.debug("Level: " + level)
                        if "dBFS" in level:
                        level = level.split("dBFS")[0]
                        level = level.replace(',', '.')
                        level = int(round(float(level)))
                        delta = target["gain"] - level
                        logging.info("Required adjustment: " + str(delta) + "n")
                        if delta is 0:
                        logging.warning(target["name"] + " is already at the correct level")
                        return 0

                        logging.info("Extracting average bitrate.n")
                        commandgetinfo = ['exiftool', target["name"]]
                        output, err, retcode = logcommand(commandgetinfo)
                        bitrate = '0'
                        for line in output.split('n'):
                        if 'Nominal Bitrate' in line:
                        bitrate = line.split(':')[1].split()[0]
                        break
                        logging.info("Average bitrate is: " + str(bitrate) + "n")
                        if bitrate is '0':
                        logging.error("No valid bitrate found, aborting conversion.n")
                        exit(-1)

                        logging.info("Re-normalizing.n")
                        commandrenormalize = ['normalize-ogg', '--ogg', '--bitrate', bitrate,
                        '-g', str(delta) + 'db', target["name"]]
                        output, err, retcode = logcommand(commandrenormalize)
                        if retcode is not 0:
                        log.error("Output:n" + output)
                        log.error("err:n" + err)
                        exit(retcode)

                        return retcode

                        # function to be mapped over
                        def parallelregain(gain=TARGET_GAIN, threads=MAX_THREADS):
                        '''parallelregain'''
                        logging.info("Creating thread pool with " + str(threads) + " elements.n")
                        pool = ThreadPool(threads)
                        targets = []
                        files_list = listdir(".")
                        files_list.sort()
                        counter = 0
                        for filename in files_list:
                        if filename.endswith("ogg"):
                        target =
                        "name":filename,
                        "gain":gain,

                        targets.append(target)
                        counter = counter + 1
                        pool.map(regain, targets)
                        pool.close()
                        pool.join()

                        if __name__ == "__main__":
                        initlogger(logfile="normalize.log", consolelevel=logging.WARNING)
                        parallelregain()





                        share|improve this answer































                          0



















                          I liked Neil's answer the most, because it doesn't introduce correlation between audio files: just pick one gain level and adjust everything to it.



                          However I had some problems parsing the output of normalize-ogg with some files I have.
                          There is also one nasty issue with bc: it doesn't do real rounding, it only truncates.



                          So eventually I gave up on shell scripting and moved to python.



                          Note1: the exiftool part might be overkill but I wanted to be 100% sure that the original bitrate would be preserved.



                          Note2: this will overwrite the originals, if you want to preserve them, use --backup in the last call to normalize-ogg. But I found more practical to keep a copy in a separate, safer, directory.



                          Note3: this solution deals with ogg files, but it's trivial to adapt it to mp3, just replace the occurrences of "ogg" with "mp3".



                          Here's my take at the problem.
                          The latest version can be found here: regain.py



                          #!/usr/bin/python3
                          """
                          Parallel normalize gains
                          """
                          '
                          This program is free software: you can redistribute it and/or modify
                          it under the terms of the GNU General Public License as published by
                          the Free Software Foundation, either version 3 of the License, or
                          (at your option) any later version.

                          This program is distributed in the hope that it will be useful,
                          but WITHOUT ANY WARRANTY; without even the implied warranty of
                          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
                          GNU General Public License for more details.

                          You should have received a copy of the GNU General Public License
                          along with this program. If not, see <http://www.gnu.org/licenses/>.
                          '

                          # Absolute value, in dB for the desired gain of each file
                          TARGET_GAIN = -12

                          #
                          MAX_THREADS = 2

                          from subprocess import Popen, PIPE
                          from multiprocessing.dummy import Pool as ThreadPool
                          from os import listdir
                          import logging

                          def initlogger(logfile="log.log", mainlevel=logging.DEBUG,
                          filelevel=logging.DEBUG, consolelevel=logging.DEBUG):
                          '''initlogger'''
                          # create logger
                          logger = logging.getLogger()
                          logger.setLevel(mainlevel)
                          # create file handler which logs even debug messages
                          fh = logging.FileHandler(logfile)
                          fh.setLevel(filelevel)
                          # create console handler also logging at DEBUG level
                          ch = logging.StreamHandler()
                          ch.setLevel(consolelevel)
                          # create formatter and add it to the handlers
                          formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
                          fh.setFormatter(formatter)
                          ch.setFormatter(formatter)
                          # add the handlers to the logger
                          logger.addHandler(fh)
                          logger.addHandler(ch)

                          def logcommand(command=[]):
                          '''logcommand'''
                          if not isinstance(command, list):
                          return "", "", -1
                          logging.info("Command:n" + " ".join(command) + "n")
                          proc = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                          output, err = proc.communicate()
                          output = output.decode("utf-8")
                          err = err.decode("utf-8")
                          logging.info("Output:n" + output + "n")
                          logging.info("Error:n" + err + "n")
                          logging.info("Return Code:n" + str(proc.returncode) + "n")
                          return output, err, proc.returncode

                          def regain(target):
                          '''regain'''
                          logging.info("============================ Start File ============================")
                          logging.warning(target["name"])
                          logging.info("Extracting gain info.n")
                          commandgetlevels = ['normalize-ogg', '-n', target["name"]]
                          output, err, retcode = logcommand(commandgetlevels)

                          level = output.split()[0]
                          logging.debug("Level: " + level)
                          if "dBFS" in level:
                          level = level.split("dBFS")[0]
                          level = level.replace(',', '.')
                          level = int(round(float(level)))
                          delta = target["gain"] - level
                          logging.info("Required adjustment: " + str(delta) + "n")
                          if delta is 0:
                          logging.warning(target["name"] + " is already at the correct level")
                          return 0

                          logging.info("Extracting average bitrate.n")
                          commandgetinfo = ['exiftool', target["name"]]
                          output, err, retcode = logcommand(commandgetinfo)
                          bitrate = '0'
                          for line in output.split('n'):
                          if 'Nominal Bitrate' in line:
                          bitrate = line.split(':')[1].split()[0]
                          break
                          logging.info("Average bitrate is: " + str(bitrate) + "n")
                          if bitrate is '0':
                          logging.error("No valid bitrate found, aborting conversion.n")
                          exit(-1)

                          logging.info("Re-normalizing.n")
                          commandrenormalize = ['normalize-ogg', '--ogg', '--bitrate', bitrate,
                          '-g', str(delta) + 'db', target["name"]]
                          output, err, retcode = logcommand(commandrenormalize)
                          if retcode is not 0:
                          log.error("Output:n" + output)
                          log.error("err:n" + err)
                          exit(retcode)

                          return retcode

                          # function to be mapped over
                          def parallelregain(gain=TARGET_GAIN, threads=MAX_THREADS):
                          '''parallelregain'''
                          logging.info("Creating thread pool with " + str(threads) + " elements.n")
                          pool = ThreadPool(threads)
                          targets = []
                          files_list = listdir(".")
                          files_list.sort()
                          counter = 0
                          for filename in files_list:
                          if filename.endswith("ogg"):
                          target =
                          "name":filename,
                          "gain":gain,

                          targets.append(target)
                          counter = counter + 1
                          pool.map(regain, targets)
                          pool.close()
                          pool.join()

                          if __name__ == "__main__":
                          initlogger(logfile="normalize.log", consolelevel=logging.WARNING)
                          parallelregain()





                          share|improve this answer





























                            0















                            0











                            0









                            I liked Neil's answer the most, because it doesn't introduce correlation between audio files: just pick one gain level and adjust everything to it.



                            However I had some problems parsing the output of normalize-ogg with some files I have.
                            There is also one nasty issue with bc: it doesn't do real rounding, it only truncates.



                            So eventually I gave up on shell scripting and moved to python.



                            Note1: the exiftool part might be overkill but I wanted to be 100% sure that the original bitrate would be preserved.



                            Note2: this will overwrite the originals, if you want to preserve them, use --backup in the last call to normalize-ogg. But I found more practical to keep a copy in a separate, safer, directory.



                            Note3: this solution deals with ogg files, but it's trivial to adapt it to mp3, just replace the occurrences of "ogg" with "mp3".



                            Here's my take at the problem.
                            The latest version can be found here: regain.py



                            #!/usr/bin/python3
                            """
                            Parallel normalize gains
                            """
                            '
                            This program is free software: you can redistribute it and/or modify
                            it under the terms of the GNU General Public License as published by
                            the Free Software Foundation, either version 3 of the License, or
                            (at your option) any later version.

                            This program is distributed in the hope that it will be useful,
                            but WITHOUT ANY WARRANTY; without even the implied warranty of
                            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
                            GNU General Public License for more details.

                            You should have received a copy of the GNU General Public License
                            along with this program. If not, see <http://www.gnu.org/licenses/>.
                            '

                            # Absolute value, in dB for the desired gain of each file
                            TARGET_GAIN = -12

                            #
                            MAX_THREADS = 2

                            from subprocess import Popen, PIPE
                            from multiprocessing.dummy import Pool as ThreadPool
                            from os import listdir
                            import logging

                            def initlogger(logfile="log.log", mainlevel=logging.DEBUG,
                            filelevel=logging.DEBUG, consolelevel=logging.DEBUG):
                            '''initlogger'''
                            # create logger
                            logger = logging.getLogger()
                            logger.setLevel(mainlevel)
                            # create file handler which logs even debug messages
                            fh = logging.FileHandler(logfile)
                            fh.setLevel(filelevel)
                            # create console handler also logging at DEBUG level
                            ch = logging.StreamHandler()
                            ch.setLevel(consolelevel)
                            # create formatter and add it to the handlers
                            formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
                            fh.setFormatter(formatter)
                            ch.setFormatter(formatter)
                            # add the handlers to the logger
                            logger.addHandler(fh)
                            logger.addHandler(ch)

                            def logcommand(command=[]):
                            '''logcommand'''
                            if not isinstance(command, list):
                            return "", "", -1
                            logging.info("Command:n" + " ".join(command) + "n")
                            proc = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                            output, err = proc.communicate()
                            output = output.decode("utf-8")
                            err = err.decode("utf-8")
                            logging.info("Output:n" + output + "n")
                            logging.info("Error:n" + err + "n")
                            logging.info("Return Code:n" + str(proc.returncode) + "n")
                            return output, err, proc.returncode

                            def regain(target):
                            '''regain'''
                            logging.info("============================ Start File ============================")
                            logging.warning(target["name"])
                            logging.info("Extracting gain info.n")
                            commandgetlevels = ['normalize-ogg', '-n', target["name"]]
                            output, err, retcode = logcommand(commandgetlevels)

                            level = output.split()[0]
                            logging.debug("Level: " + level)
                            if "dBFS" in level:
                            level = level.split("dBFS")[0]
                            level = level.replace(',', '.')
                            level = int(round(float(level)))
                            delta = target["gain"] - level
                            logging.info("Required adjustment: " + str(delta) + "n")
                            if delta is 0:
                            logging.warning(target["name"] + " is already at the correct level")
                            return 0

                            logging.info("Extracting average bitrate.n")
                            commandgetinfo = ['exiftool', target["name"]]
                            output, err, retcode = logcommand(commandgetinfo)
                            bitrate = '0'
                            for line in output.split('n'):
                            if 'Nominal Bitrate' in line:
                            bitrate = line.split(':')[1].split()[0]
                            break
                            logging.info("Average bitrate is: " + str(bitrate) + "n")
                            if bitrate is '0':
                            logging.error("No valid bitrate found, aborting conversion.n")
                            exit(-1)

                            logging.info("Re-normalizing.n")
                            commandrenormalize = ['normalize-ogg', '--ogg', '--bitrate', bitrate,
                            '-g', str(delta) + 'db', target["name"]]
                            output, err, retcode = logcommand(commandrenormalize)
                            if retcode is not 0:
                            log.error("Output:n" + output)
                            log.error("err:n" + err)
                            exit(retcode)

                            return retcode

                            # function to be mapped over
                            def parallelregain(gain=TARGET_GAIN, threads=MAX_THREADS):
                            '''parallelregain'''
                            logging.info("Creating thread pool with " + str(threads) + " elements.n")
                            pool = ThreadPool(threads)
                            targets = []
                            files_list = listdir(".")
                            files_list.sort()
                            counter = 0
                            for filename in files_list:
                            if filename.endswith("ogg"):
                            target =
                            "name":filename,
                            "gain":gain,

                            targets.append(target)
                            counter = counter + 1
                            pool.map(regain, targets)
                            pool.close()
                            pool.join()

                            if __name__ == "__main__":
                            initlogger(logfile="normalize.log", consolelevel=logging.WARNING)
                            parallelregain()





                            share|improve this answer
















                            I liked Neil's answer the most, because it doesn't introduce correlation between audio files: just pick one gain level and adjust everything to it.



                            However I had some problems parsing the output of normalize-ogg with some files I have.
                            There is also one nasty issue with bc: it doesn't do real rounding, it only truncates.



                            So eventually I gave up on shell scripting and moved to python.



                            Note1: the exiftool part might be overkill but I wanted to be 100% sure that the original bitrate would be preserved.



                            Note2: this will overwrite the originals, if you want to preserve them, use --backup in the last call to normalize-ogg. But I found more practical to keep a copy in a separate, safer, directory.



                            Note3: this solution deals with ogg files, but it's trivial to adapt it to mp3, just replace the occurrences of "ogg" with "mp3".



                            Here's my take at the problem.
                            The latest version can be found here: regain.py



                            #!/usr/bin/python3
                            """
                            Parallel normalize gains
                            """
                            '
                            This program is free software: you can redistribute it and/or modify
                            it under the terms of the GNU General Public License as published by
                            the Free Software Foundation, either version 3 of the License, or
                            (at your option) any later version.

                            This program is distributed in the hope that it will be useful,
                            but WITHOUT ANY WARRANTY; without even the implied warranty of
                            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
                            GNU General Public License for more details.

                            You should have received a copy of the GNU General Public License
                            along with this program. If not, see <http://www.gnu.org/licenses/>.
                            '

                            # Absolute value, in dB for the desired gain of each file
                            TARGET_GAIN = -12

                            #
                            MAX_THREADS = 2

                            from subprocess import Popen, PIPE
                            from multiprocessing.dummy import Pool as ThreadPool
                            from os import listdir
                            import logging

                            def initlogger(logfile="log.log", mainlevel=logging.DEBUG,
                            filelevel=logging.DEBUG, consolelevel=logging.DEBUG):
                            '''initlogger'''
                            # create logger
                            logger = logging.getLogger()
                            logger.setLevel(mainlevel)
                            # create file handler which logs even debug messages
                            fh = logging.FileHandler(logfile)
                            fh.setLevel(filelevel)
                            # create console handler also logging at DEBUG level
                            ch = logging.StreamHandler()
                            ch.setLevel(consolelevel)
                            # create formatter and add it to the handlers
                            formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
                            fh.setFormatter(formatter)
                            ch.setFormatter(formatter)
                            # add the handlers to the logger
                            logger.addHandler(fh)
                            logger.addHandler(ch)

                            def logcommand(command=[]):
                            '''logcommand'''
                            if not isinstance(command, list):
                            return "", "", -1
                            logging.info("Command:n" + " ".join(command) + "n")
                            proc = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                            output, err = proc.communicate()
                            output = output.decode("utf-8")
                            err = err.decode("utf-8")
                            logging.info("Output:n" + output + "n")
                            logging.info("Error:n" + err + "n")
                            logging.info("Return Code:n" + str(proc.returncode) + "n")
                            return output, err, proc.returncode

                            def regain(target):
                            '''regain'''
                            logging.info("============================ Start File ============================")
                            logging.warning(target["name"])
                            logging.info("Extracting gain info.n")
                            commandgetlevels = ['normalize-ogg', '-n', target["name"]]
                            output, err, retcode = logcommand(commandgetlevels)

                            level = output.split()[0]
                            logging.debug("Level: " + level)
                            if "dBFS" in level:
                            level = level.split("dBFS")[0]
                            level = level.replace(',', '.')
                            level = int(round(float(level)))
                            delta = target["gain"] - level
                            logging.info("Required adjustment: " + str(delta) + "n")
                            if delta is 0:
                            logging.warning(target["name"] + " is already at the correct level")
                            return 0

                            logging.info("Extracting average bitrate.n")
                            commandgetinfo = ['exiftool', target["name"]]
                            output, err, retcode = logcommand(commandgetinfo)
                            bitrate = '0'
                            for line in output.split('n'):
                            if 'Nominal Bitrate' in line:
                            bitrate = line.split(':')[1].split()[0]
                            break
                            logging.info("Average bitrate is: " + str(bitrate) + "n")
                            if bitrate is '0':
                            logging.error("No valid bitrate found, aborting conversion.n")
                            exit(-1)

                            logging.info("Re-normalizing.n")
                            commandrenormalize = ['normalize-ogg', '--ogg', '--bitrate', bitrate,
                            '-g', str(delta) + 'db', target["name"]]
                            output, err, retcode = logcommand(commandrenormalize)
                            if retcode is not 0:
                            log.error("Output:n" + output)
                            log.error("err:n" + err)
                            exit(retcode)

                            return retcode

                            # function to be mapped over
                            def parallelregain(gain=TARGET_GAIN, threads=MAX_THREADS):
                            '''parallelregain'''
                            logging.info("Creating thread pool with " + str(threads) + " elements.n")
                            pool = ThreadPool(threads)
                            targets = []
                            files_list = listdir(".")
                            files_list.sort()
                            counter = 0
                            for filename in files_list:
                            if filename.endswith("ogg"):
                            target =
                            "name":filename,
                            "gain":gain,

                            targets.append(target)
                            counter = counter + 1
                            pool.map(regain, targets)
                            pool.close()
                            pool.join()

                            if __name__ == "__main__":
                            initlogger(logfile="normalize.log", consolelevel=logging.WARNING)
                            parallelregain()






                            share|improve this answer















                            share|improve this answer




                            share|improve this answer








                            edited Apr 30 '17 at 10:52

























                            answered Apr 23 '17 at 15:48









                            Igor StoppaIgor Stoppa

                            1013 bronze badges




                            1013 bronze badges































                                draft saved

                                draft discarded















































                                Thanks for contributing an answer to Ask Ubuntu!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f246242%2fhow-to-normalize-sound-in-mp3-files%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown









                                Popular posts from this blog

                                Distance measures on a map of a game The 2019 Stack Overflow Developer Survey Results Are Inmin distance in a graphShortest distance path on contour plotHow to plot a tilted map?Finding points outside of a diskDelaunay link distanceAnnulus from GeoDisks: drawing a ring on a mapNegative Correlation DistanceFind distance along a path (GPS coordinates)Finding position at given distance in a GeoPathMathematics behind distance estimation using camera

                                How to get a smooth, uniform ParametricPlot of a 2D Region?How to plot a complicated Region?How to exclude a region from ParametricPlotHow discretize a region placing vertices on a specific non-uniform gridHow to transform a Plot or a ParametricPlot into a RegionHow can I get a smooth plot of a bounded region?Smooth ParametricPlot3D with RegionFunction?Smooth border of a region ParametricPlotSmooth region boundarySmooth region plot from list of pointsGet minimum y of a certain x in a region

                                Genealogie vun de Merowenger Vum Merowech bis zum Chilperich I. | Navigatiounsmenü