Search code examples
pythonaudiopydub

How to get the peak of an audio file in python?


How could I get the dB value of the peak of a wav file (for example, the peak of some wav file could be -6db, aka its loudest point is -6db) using python?


Solution

  • here is an example of using wave, struct and math in Python to get the peak of an audio file.

    import wave
    import struct
    import math
    
    # Open the audio file
    with wave.open('audio.wav', 'r') as audio:
        # Extract the raw audio data
        raw_data = audio.readframes(audio.getnframes())
    
    # Convert the raw audio data to a list of integers
    samples = struct.unpack('{n}h'.format(n=audio.getnframes()), raw_data)
    
    # Find the peak sample
    peak = max(samples)
    
    # Calculate the reference value based on the bit depth of the audio file
    reference_value = 2**(audio.getsampwidth() * 8 - 1)
    
    # Calculate the peak value in dBFS, using the maximum possible sample value as the reference value
    peak_dB = 20 * math.log10(peak / reference_value)
    
    print(peak_dB)