Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pydub set the maximum/minimum volume?

As title, can I set a value for maximum/minimum volume, that is, there won't be too loud or too quiet in output audio file? (Not normalize, I just want tune the specific volume to normal, as the photo below.)

enter image description here

like image 751
Leo Hsieh Avatar asked Oct 27 '25 12:10

Leo Hsieh


1 Answers

Loudness is a little complicated - a simple solution is to measure using one of the simpler methods like dBFS and set the gain on all your audio to match.

sounds = [audio_segment1, audio_segment2, audio_segment3, audio_segment4]

def set_loudness(sound, target_dBFS):
    loudness_difference = target_dBFS - sound.dBFS
    return sound.apply_gain(loudness_difference)

# -20dBFS is relatively quiet, but very likely to be enough headroom    
same_loudness_sounds = [
    set_loudness(sound, target_dBFS=-20)
    for sound in sounds
]

One complicating factor is that some of your sounds may have extended portions of silence, or even just very quiet parts. That would pull down the average, and you may have to write a more sophisticated loudness measurement. Again, a simple way, you can slice the sound into shorter pieces and simply use the loudest one assuming your whole sound is 15 minutes long, we can take 1 minute slices:

from pydub.utils import make_chunks

def get_loudness(sound, slice_size=60*1000):
    return max(chunk.dBFS for chunk in make_chunks(sound, slice_size))


# ...and replace set_loudness() in above example with…
def set_loudness(sound, target_dBFS):
    loudness_difference = target_dBFS - get_loudness(sound)
    return sound.apply_gain(loudness_difference)
like image 180
Jiaaro Avatar answered Oct 30 '25 03:10

Jiaaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!