Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 981fa9b

Browse files
authoredNov 4, 2024··
Update butterworth_filter.py
1 parent a19bede commit 981fa9b

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed
 

‎audio_filters/butterworth_filter.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
from math import cos, sin, sqrt, tau
2-
32
from audio_filters.iir_filter import IIRFilter
43

54
"""
65
Create 2nd-order IIR filters with Butterworth design.
76
87
Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html
9-
Alternatively you can use scipy.signal.butter, which should yield the same results.
8+
Alternatively, you can use scipy.signal.butter, which should yield the same results.
109
"""
1110

12-
1311
def make_lowpass(
1412
frequency: int,
1513
samplerate: int,
@@ -208,27 +206,32 @@ def make_highshelf(
208206
209207
>>> filter = make_highshelf(1000, 48000, 6)
210208
>>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE
211-
[2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543,
212-
-7.922740859457287, 3.6756456963725253]
209+
[2.2229172136088806, -3.616080374557819, 1.4122939941901636, 0.5690651073937642,
210+
-1.3335115824061685, 0.7666141956641752]
213211
"""
214212
w0 = tau * frequency / samplerate
215213
_sin = sin(w0)
216214
_cos = cos(w0)
217215
alpha = _sin / (2 * q_factor)
218216
big_a = 10 ** (gain_db / 40)
219-
pmc = (big_a + 1) - (big_a - 1) * _cos
220-
ppmc = (big_a + 1) + (big_a - 1) * _cos
221-
mpc = (big_a - 1) - (big_a + 1) * _cos
222-
pmpc = (big_a - 1) + (big_a + 1) * _cos
217+
pmc = (big_a + 1) + (big_a - 1) * _cos
218+
ppmc = (big_a + 1) - (big_a - 1) * _cos
219+
mpc = (big_a - 1) + (big_a + 1) * _cos
220+
pmpc = (big_a - 1) - (big_a + 1) * _cos
223221
aa2 = 2 * sqrt(big_a) * alpha
224222

225-
b0 = big_a * (ppmc + aa2)
226-
b1 = -2 * big_a * pmpc
227-
b2 = big_a * (ppmc - aa2)
228-
a0 = pmc + aa2
229-
a1 = 2 * mpc
230-
a2 = pmc - aa2
223+
b0 = big_a * (pmc - aa2)
224+
b1 = -2 * big_a * mpc
225+
b2 = big_a * (pmc + aa2)
226+
a0 = ppmc - aa2
227+
a1 = 2 * pmpc
228+
a2 = ppmc + aa2
231229

232230
filt = IIRFilter(2)
233231
filt.set_coefficients([a0, a1, a2], [b0, b1, b2])
234232
return filt
233+
234+
235+
if __name__ == "__main__":
236+
import doctest
237+
doctest.testmod()

0 commit comments

Comments
 (0)
Please sign in to comment.