Skip to content

Instantly share code, notes, and snippets.

@dcalacci
Created May 15, 2015 16:48
Show Gist options
  • Save dcalacci/549f70a28200cbceb648 to your computer and use it in GitHub Desktop.
Save dcalacci/549f70a28200cbceb648 to your computer and use it in GitHub Desktop.
band pass filter on 1s of data, returning a list of average amplitudes for each 100ms of data in a 1s sample.
import numpy as np
from scipy.signal import butter, lfilter, freqz, medfilt
from collections import namedtuple
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = lfilter(b, a, data)
return y
# for 'low', 'med', and 'high' bands in daniel's thesis.
Band = namedtuple('band', ['low', 'high'])
bands = [Band(85, 222), Band(222, 583), Band(583, 1527), Band(1527, 4000)]
SAMPLERATE = 8000
#SPEAKING_THRESHOLD = 400
def filter_audio(data):
# 85 to 583, playing around with constants in daniel's thesis
signal = butter_bandpass_filter(data, 85, 583, SAMPLERATE)
# median filter with a window length of 81 samples
# each data array has 8000 samples, so we're doing 1/100 of the total length
signal = medfilt(signal, 81)
# # maybe zero values below a threshold?
# zero_indices = signal < SPEAKING_THRESHOLD
# signal[zero_indices] = 0
return signal
def filter_amplitudes(data):
""" we get 1s of data. split into 'samples' that are 1/10 second each, and calculate avg. amplitude.
"""
filtered_signal = filter_audio(data)
samplesPerAmplitude = 0.1 * 8000
amplitudes = []
sampleSum = 0
for i in xrange(len(filtered_signal)):
if (i % samplesPerAmplitude == 0 and i > 0):
amplitudes.append(sampleSum / samplesPerAmplitude)
sampleSum = 0
else:
sampleSum += abs(filtered_signal[i])
if sampleSum != 0:
amplitudes.append(sampleSum / samplesPerAmplitude)
return amplitudes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment