public
Last active

A-weighting audio files in Python

  • Download Gist
A_weighting.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Originally a MATLAB script. Also included ASPEC, CDSGN, CSPEC.
 
Author: Christophe Couvreur, Faculte Polytechnique de Mons (Belgium)
couvreur@thor.fpms.ac.be
Last modification: Aug. 20, 1997, 10:00am.
 
http://www.mathworks.com/matlabcentral/fileexchange/69
http://replaygain.hydrogenaudio.org/mfiles/adsgn.m
Translated from adsgn.m to Python 2009-07-14 endolith@gmail.com
"""
 
from numpy import pi, convolve
from scipy.signal.filter_design import bilinear
from scipy.signal import lfilter
 
def A_weighting(Fs):
"""Design of an A-weighting filter.
B, A = A_weighting(Fs) designs a digital A-weighting filter for
sampling frequency Fs. Usage: y = lfilter(B, A, x).
Warning: Fs should normally be higher than 20 kHz. For example,
Fs = 48000 yields a class 1-compliant filter.
 
References:
[1] IEC/CD 1672: Electroacoustics-Sound Level Meters, Nov. 1996.
"""
# Definition of analog A-weighting filter according to IEC/CD 1672.
f1 = 20.598997
f2 = 107.65265
f3 = 737.86223
f4 = 12194.217
A1000 = 1.9997
NUMs = [(2 * pi * f4)**2 * (10**(A1000/20)), 0, 0, 0, 0]
DENs = convolve([1, +4 * pi * f4, (2 * pi * f4)**2],
[1, +4 * pi * f1, (2 * pi * f1)**2], mode='full')
DENs = convolve(convolve(DENs, [1, 2 * pi * f3], mode='full'),
[1, 2 * pi * f2], mode='full')
# Use the bilinear transformation to get the digital filter.
# (Octave, MATLAB, and PyLab disagree about Fs vs 1/Fs)
return bilinear(NUMs, DENs, Fs)
 
# You probably need to specify the axis. Importing a stereo sound file with scikits.audiolab needs axis = 0, for instance:
# y = lfilter(B, A, x, axis = 0)
analyzer.m
Matlab
1 2 3 4 5 6 7 8 9
filename = 'noise.wav'
[Y,FS,BITS] = wavread(filename);
p = leq(Y,1000);
level = mean(p)
[B,A] = adsgn(FS);
x = filter(B,A,Y);
pA = leq(x,1000);
levelA = mean(pA)
wavwrite(x,FS,BITS,'weightednoise.wav')
analyzer.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# This may or may not work
 
from scikits.audiolab import wavread, wavwrite
from numpy import mean
from A_weighting import A_weighting
 
filename = 'noise.wav'
y, Fs, bits = wavread(filename)
p = leq(Y,1000) #???
level = mean(p)
B, A = A_weighting(Fs)
x = lfilter(B, A, y)
pA = leq(x,1000) #???
levelA = mean(pA)
wavwrite(x, fs, bits, 'weightednoise.wav')
readme.md
Markdown

Zeokat thanks for the code, will test it.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.