18

I have a bunch of AAC (.m4a) audio files that need to be normalized, and was hoping to find a way to do it with a simple python script using some package.

I found this thread on superuser where someone has written an ffmpeg command-line utility in python, and it works well, but was wondering if there is some currently available python package with a pip install that would be up to the task.

Luke Davis
  • 2,548
  • 2
  • 21
  • 43

2 Answers2

26
from pydub import AudioSegment, effects  

rawsound = AudioSegment.from_file("./input.m4a", "m4a")  
normalizedsound = effects.normalize(rawsound)  
normalizedsound.export("./output.wav", format="wav")

Before:

Before image

After:

After image

Oddthinking
  • 24,359
  • 19
  • 83
  • 121
WeiJian Yen
  • 261
  • 3
  • 3
19

You can use pydub module to achieve normalization of peak volume with least amount of code. Install pydub using

pip install pydub

Inspiration from here

You can measure rms in pydub which is a measure of average amplitude, which pydub provides as audio_segment.rms. It also provides a convenient method to convert values to dBFS (audio_segment.dBFS)

If you want an audio file to be the same average amplitude, basically you choose an average amplitude (in dBFS, -20 in the example below), and adjust as needed:

from pydub import AudioSegment

def match_target_amplitude(sound, target_dBFS):
    change_in_dBFS = target_dBFS - sound.dBFS
    return sound.apply_gain(change_in_dBFS)

sound = AudioSegment.from_file("yourAudio.m4a", "m4a")
normalized_sound = match_target_amplitude(sound, -20.0)
normalized_sound.export("nomrmalizedAudio.m4a", format="mp4")
Anil_M
  • 10,893
  • 6
  • 47
  • 74
  • 1
    Dangerous: The function match_target_amplitude will create a unusable audio file if you pass wrong parameters. By "normalize the volume" most understand an automatic change of the audio file without the normalization function causing the result to be unusable. If one can give parameters to a normalization function, then they are hints, but they never lead to the result being unusable. If one has to open an Audio File Editor to validate the normalized result, then it does not make any sense to use functions like match_target_amplitude because Audio Editors usually offer the function, too. – Tom Apr 25 '23 at 09:08