Audio volume normalize python

I have multiple wave files, some are small volume and others are large volume.

I want to “Normalize” sound amplitude.

(Like the “Normalize” function that Some audio sequencer application has. Making volume bigger to the peak comes to the 0db.)

For example librosa library, it has librosa.util.normalize, however I am not sure it is what I meant.

I want to align the volume of audio, is there any practice?

Answer

Find the maximum peak (positive or negative, so use abs) in any channel. For instance in a 16 bits file, imagine you find 25000. Compute the ratio of that value relatively to the maximum in the signed 16 bit range and invert it :

ratio = 32767.0 / 25000 #(equivalent to 1 / (25000 / 32767.0))

Now iterate all samples and multiply them by the inverted ratio so that 25000 becomes 32767 :

for(sample in samples):
    sample = round(sample * ratio)

This operation is called “normalization” or “optimization” depending on the software.