Search code examples
pythonaudiolimitvolumepydub

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


Solution

  • This is what I do, and it works well for me. The shortcoming is the bad performance if the sample_rate is too small.

    from pydub import AudioSegment
    from pydub.utils import make_chunks
    
    def match_target_amplitude(sound, target_dBFS):
        change_in_dBFS = target_dBFS - sound.dBFS
        return sound.apply_gain(change_in_dBFS)
    
    def sound_slice_normalize(sound, sample_rate, target_dBFS):
        def max_min_volume(min, max):
            for chunk in make_chunks(sound, sample_rate):
                if chunk.dBFS < min:
                    yield match_target_amplitude(chunk, min)
                elif chunk.dBFS > max:
                    yield match_target_amplitude(chunk, max)
                else:
                    yield chunk
    
        return reduce(lambda x, y: x + y, max_min_volume(target_dBFS[0], target_dBFS[1]))
    
    sound = AudioSegment.from_mp3("vanilla_sky.mp3")
    normalized_db = min_normalized_db, max_normalized_db = [-32.0, -18.0]
    sample_rate = 1000
    normalized_sound = sound_slice_normalize(sound, sample_rate, normalized_db)