import math
import audioop


def get_noise_level(stream, nsamples=50, chunk=1024):
    """
        Gets average audio intensity of your mic sound.
        The average is the avg of the 20% largest intensities recorded.
    """
    values = [math.sqrt(abs(audioop.avg(stream.read(chunk), 4)))
              for x in range(nsamples)]
    values = sorted(values, reverse=True)
    r = sum(values[:int(nsamples * 0.2)])/int(nsamples * 0.2)
    return r