def test_all_available_presets(self): f = digital_filter(7) for sr in [8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 192000]: f.set_a_weighting(sr) f = digital_filter(5) for sr in [8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 192000]: f.set_c_weighting(sr)
def apply_filter(path): from aubio import source, sink, digital_filter from os.path import basename, splitext # open input file, get its samplerate s = source(path) samplerate = s.samplerate # create an A-weighting filter f = digital_filter(7) f.set_a_weighting(samplerate) # alternatively, apply another filter # create output file o = sink("filtered_" + splitext(basename(path))[0] + ".wav", samplerate) total_frames = 0 while True: samples, read = s() filtered_samples = f(samples) o(filtered_samples, read) total_frames += read if read < s.hop_size: break duration = total_frames / float(samplerate) print("read {:s}".format(s.uri)) print("applied A-weighting filtered ({:d} Hz)".format(samplerate)) print("wrote {:s} ({:.2f} s)".format(o.uri, duration))
def apply_filter(self): # open input file, get its samplerate s = aubio.source(self.path) samplerate = s.samplerate # create an A-weighting filter f = aubio.digital_filter(7) f.set_a_weighting(samplerate) # create output file and replace original uploaded by user. Append the word filter to end of filename new_file_path = self.path[:-4] new_file_path += "_filter.wav" o = aubio.sink(new_file_path, samplerate) total_frames = 0 while True: # read from source samples, read = s() # filter samples filtered_samples = f(samples) # write to sink o(filtered_samples, read) # count frames read total_frames += read # end of file reached if read < s.hop_size: break
def apply_filter(path, target): # open input file, get its samplerate s = aubio.source(path) samplerate = s.samplerate # create an A-weighting filter f = aubio.digital_filter(7) f.set_a_weighting(samplerate) # create output file o = aubio.sink(target, samplerate) total_frames = 0 while True: # read from source samples, read = s() # filter samples filtered_samples = f(samples) # write to sink o(filtered_samples, read) # count frames read total_frames += read # end of file reached if read < s.hop_size: break # print some info duration = total_frames / float(samplerate) input_str = "input: {:s} ({:.2f} s, {:d} Hz)" output_str = "output: {:s}, A-weighting filtered ({:d} frames total)" print(input_str.format(s.uri, duration, samplerate)) print(output_str.format(o.uri, total_frames))
def applyFilter(path, target): # open input file, get its samplerate s = source(path) samplerate = s.samplerate # create an A-weighting filter f = digital_filter(7) f.set_a_weighting(samplerate) # create output file o = sink(target, samplerate) total_frames = 0 while True: # read from source samples, read = s() # filter samples filtered_samples = f(samples) # write to sink o(filtered_samples, read) # count frames read total_frames += read # end of file reached if read < s.hop_size: break
def apply_filter(path): from aubio import source, sink, digital_filter from os.path import basename, splitext # open input file, get its samplerate s = source(path) samplerate = s.samplerate # create an A-weighting filter f = digital_filter(7) f.set_a_weighting(samplerate) # alternatively, apply another filter # create output file o = sink("filtered_" + splitext(basename(path))[0] + ".wav", samplerate) total_frames = 0 while True: samples, read = s() filtered_samples = f(samples) o(filtered_samples, read) total_frames += read if read < s.hop_size: break duration = total_frames / float(samplerate) print ("read {:s}".format(s.uri)) print ("applied A-weighting filtered ({:d} Hz)".format(samplerate)) print ("wrote {:s} ({:.2f} s)".format(o.uri, duration))
def test_a_weighting(self): expected = array_from_text_file('a_weighting_test_simple.expected') f = digital_filter(7) f.set_a_weighting(44100) v = fvec(32) v[12] = .5 u = f(v) assert_almost_equal (expected[1], u)
def test_c_weighting_8000(self): expected = array_from_text_file('c_weighting_test_simple_8000.expected') f = digital_filter(5) f.set_c_weighting(8000) v = fvec(32) v[12] = .5 u = f(v) assert_almost_equal (expected[1], u)
def activate(self): if self._audio is None: self._audio = pyaudio.PyAudio() # Setup a pre-emphasis filter to help balance the highs self.pre_emphasis = None if self._config['pre_emphasis']: self.pre_emphasis = aubio.digital_filter(3) # old, do not use #self.pre_emphasis.set_biquad(1., -self._config['pre_emphasis'], 0, 0, 0) # USE THESE FOR SCOTT_MEL OR OTHERS #self.pre_emphasis.set_biquad(1.3662, -1.9256, 0.5621, -1.9256, 0.9283) # USE THESE FOR MATT_MEl # weaker bass, good for vocals, highs #self.pre_emphasis.set_biquad(0.87492, -1.74984, 0.87492, -1.74799, 0.75169) # bass heavier overall more balanced self.pre_emphasis.set_biquad(0.85870, -1.71740, 0.85870, -1.71605, 0.71874) # Setup the phase vocoder to perform a windowed FFT self._phase_vocoder = aubio.pvoc( self._config['fft_size'], self._config['mic_rate'] // self._config['sample_rate']) self._frequency_domain_null = aubio.cvec(self._config['fft_size']) self._frequency_domain = self._frequency_domain_null self._frequency_domain_x = np.linspace( 0, self._config['mic_rate'], (self._config["fft_size"] // 2) + 1) # Enumerate all of the input devices and find the one matching the # configured device index _LOGGER.info("Audio Input Devices:") info = self._audio.get_host_api_info_by_index(0) for i in range(0, info.get('deviceCount')): if (self._audio.get_device_info_by_host_api_device_index( 0, i).get('maxInputChannels')) > 0: _LOGGER.info(" [{}] {}".format( i, self._audio.get_device_info_by_host_api_device_index( 0, i).get('name'))) # Open the audio stream and start processing the input self._stream = self._audio.open( input_device_index=self._config['device_index'], format=pyaudio.paFloat32, channels=1, rate=self._config['mic_rate'], input=True, frames_per_buffer=self._config['mic_rate'] // self._config['sample_rate'], stream_callback=self._audio_sample_callback) self._stream.start_stream() _LOGGER.info("Audio source opened.")
def activate(self): if self._audio is None: self._audio = pyaudio.PyAudio() # Setup a pre-emphasis filter to help balance the highs self.pre_emphasis = None if self._config['pre_emphasis']: self.pre_emphasis = aubio.digital_filter(3) self.pre_emphasis.set_biquad(1., -self._config['pre_emphasis'], 0, 0, 0) # Setup the phase vocoder to perform a windowed FFT self._phase_vocoder = aubio.pvoc( self._config['fft_size'], self._config['mic_rate'] // self._config['sample_rate']) self._frequency_domain_null = aubio.cvec(self._config['fft_size']) self._frequency_domain = self._frequency_domain_null self._frequency_domain_x = np.linspace( 0, self._config['mic_rate'], (self._config["fft_size"] // 2) + 1) # Enumerate all of the input devices and find the one matching the # configured device index _LOGGER.info("Audio Input Devices:") info = self._audio.get_host_api_info_by_index(0) for i in range(0, info.get('deviceCount')): if (self._audio.get_device_info_by_host_api_device_index( 0, i).get('maxInputChannels')) > 0: _LOGGER.info(" [{}] {}".format( i, self._audio.get_device_info_by_host_api_device_index( 0, i).get('name'))) # PyAudio may segfault, reset device index if it seems implausible if self._config['device_index'] >= info.get( 'deviceCount' ) or self._audio.get_device_info_by_host_api_device_index( 0, self._config['device_index']).get('maxInputChannels') <= 0: _LOGGER.warn("Invalid device_index setting, resetting it to 0") self._config['device_index'] = 0 # Open the audio stream and start processing the input self._stream = self._audio.open( input_device_index=self._config['device_index'], format=pyaudio.paFloat32, channels=1, rate=self._config['mic_rate'], input=True, frames_per_buffer=self._config['mic_rate'] // self._config['sample_rate'], stream_callback=self._audio_sample_callback) self._stream.start_stream() _LOGGER.info("Audio source opened.")
def test_a_weighting_parted(self): expected = array_from_text_file('a_weighting_test_simple.expected') f = digital_filter(7) f.set_a_weighting(44100) v = fvec(16) v[12] = .5 u = f(v) assert_almost_equal (expected[1][:16], u) # one more time v = fvec(16) u = f(v) assert_almost_equal (expected[1][16:], u)
def __init__(self, **kwargs) -> None: super().__init__() self.sample_rate = kwargs.get('sample_rate', 44100) self.buffer_size = kwargs.get('buffer_size', 1024) self.pa = PyAudio() self.pitch = pitch('default', self.buffer_size, self.buffer_size // 2, self.sample_rate) self.pitch.set_unit('midi') self.pitch.set_tolerance(0.7) self.tempo = tempo('default', self.buffer_size, self.buffer_size // 2, self.sample_rate) low_filter = digital_filter(3) low_filter.set_biquad(7.89276652e-4, 0.00157855, 7.89276652e-4, -1.94146067, 0.94461777) mid_filter = digital_filter(3) mid_filter.set_biquad(0.13357629, 0.0, -0.13357629, -1.64841689, 0.73284743) high_filter = digital_filter(3) high_filter.set_biquad(0.72530667, -1.45061333, 0.72530667, -1.32614493, 0.57508174) self.filters = [low_filter, mid_filter, high_filter] self.stream = None
def test_cweighting_error(self): f = digital_filter (2) self.assertRaises ( ValueError, f.set_c_weighting, 44100 ) f = digital_filter (8) self.assertRaises ( ValueError, f.set_c_weighting, 44100 ) f = digital_filter (5) self.assertRaises ( ValueError, f.set_c_weighting, 4000 ) f = digital_filter (5) self.assertRaises ( ValueError, f.set_c_weighting, 193000 ) f = digital_filter (7) self.assertRaises ( ValueError, f.set_a_weighting, 193000 ) f = digital_filter (5) self.assertRaises ( ValueError, f.set_a_weighting, 192000 )
def apply_filter(path, params={}): from aubio import source, sink, digital_filter from os.path import basename, splitex, splitextt s = source(path) f = digital_filter(7) f.set_a_weighting(s.samplerate) #f = digital_filter(3) #f.set_biquad(...) o = sink("filtered_" + splitext(basename(path))[0] + ".wav") # Total number of frames read total_frames = 0 while True: samples, read = s() filtered_samples = f(samples) o(samples, read) total_frames += read if read < s.hop_size: break print "filtered", s.uri, "to", o.uri, "using an A-weighting filter"
def apply_filter(path, params = {}): from aubio import source, sink, digital_filter from os.path import basename, splitex, splitextt s = source(path) f = digital_filter(7) f.set_a_weighting(s.samplerate) #f = digital_filter(3) #f.set_biquad(...) o = sink("filtered_" + splitext(basename(path))[0] + ".wav") # Total number of frames read total_frames = 0 while True: samples, read = s() filtered_samples = f(samples) o(samples, read) total_frames += read if read < s.hop_size: break print "filtered", s.uri, "to", o.uri, "using an A-weighting filter"
def audio_filter(self): """ Taken from https://github.com/aubio/aubio/tree/master/python/demos This was used for testing high and low pass filters which clean up the unwanted low and high frequencies. This was done in an attempt to remove unwanted noise from the microphone signal. It may be useful in the future """ # open input file, get its samplerate s = aubio.source(self.filename) samplerate = s.samplerate target = "./audio/filteredAudio/filter.wav" # A-weighting filter is 7, C-weighting is 5 # See https://en.wikipedia.org/wiki/A-weighting for a brief overview f = aubio.digital_filter(7) f.set_a_weighting(samplerate) # create output file o = aubio.sink(target, samplerate) total_frames = 0 while True: # read from source samples, read = s() # filter samples filtered_samples = f(samples) # write to sink o(filtered_samples, read) # count frames read total_frames += read # end of file reached if read < s.hop_size: break # print some info duration = total_frames / float(samplerate) input_str = "input: {:s} ({:.2f} s, {:d} Hz)" output_str = "output: {:s}, A-weighting filtered ({:d} frames total)" print(input_str.format(s.uri, duration, samplerate)) print(output_str.format(o.uri, total_frames))
def test_members(self): f = digital_filter() assert_equal (f.order, 7) f = digital_filter(5) assert_equal (f.order, 5) f(fvec())
def test_negative_order(self): with self.assertRaises(ValueError): digital_filter(-1)
def test_set_biquad_wrong_order(self): f = digital_filter(4) with self.assertRaises(ValueError): f.set_biquad(0., 0., 0, 0., 0.)
def test_set_biquad(self): f = digital_filter(3) f.set_biquad(0., 0., 0, 0., 0.)
def activate(self): if self._audio is None: self._audio = pyaudio.PyAudio() # Setup a pre-emphasis filter to help balance the highs self.pre_emphasis = None if self._config["pre_emphasis"]: self.pre_emphasis = aubio.digital_filter(3) # # old, do not use # self.pre_emphasis.set_biquad(1., -self._config['pre_emphasis'], 0, 0, 0) # USE THESE FOR SCOTT_MEL OR OTHERS # self.pre_emphasis.set_biquad(1.3662, -1.9256, 0.5621, -1.9256, 0.9283) # USE THESE FOR MATT_MEl # weaker bass, good for vocals, highs # self.pre_emphasis.set_biquad(0.87492, -1.74984, 0.87492, -1.74799, 0.75169) # bass heavier overall more balanced self.pre_emphasis.set_biquad(0.85870, -1.71740, 0.85870, -1.71605, 0.71874) # Setup the phase vocoder to perform a windowed FFT self._phase_vocoder = aubio.pvoc( self._config["fft_size"], self._config["mic_rate"] // self._config["sample_rate"], ) self._frequency_domain_null = aubio.cvec(self._config["fft_size"]) self._frequency_domain = self._frequency_domain_null self._frequency_domain_x = np.linspace( 0, self._config["mic_rate"], (self._config["fft_size"] // 2) + 1, ) # Enumerate all of the input devices and find the one matching the # configured device index _LOGGER.info("Audio Input Devices:") currentIndex = self._config.get("device_index", -1) for apiIndex in range(self._audio.get_host_api_count()): info = self._audio.get_host_api_info_by_index(apiIndex) for i in range(0, info.get("deviceCount")): deviceInfo = ( self._audio.get_device_info_by_host_api_device_index( apiIndex, i)) if deviceInfo.get("maxInputChannels") > 0: _LOGGER.info(" [{}] {}".format(i, deviceInfo.get("name"))) if (self._config.get("device_name", "") == deviceInfo.get("name") and int( self._config.get("host_api", 0)) == apiIndex): currentIndex = deviceInfo["index"] _LOGGER.info("Found audio device under index: %s", currentIndex) # we need to check if the index is valid to avoid a crash try: self._audio.get_device_info_by_index(currentIndex) except OSError: _LOGGER.warn("Could not open audio device, fall back to default") currentIndex = 0 # Open the audio stream and start processing the input try: self._stream = self._audio.open( input_device_index=currentIndex, format=pyaudio.paFloat32, channels=1, rate=self._config["mic_rate"], input=True, frames_per_buffer=self._config["mic_rate"] // self._config["sample_rate"], stream_callback=self._audio_sample_callback, ) self._stream.start_stream() except OSError: _LOGGER.critical("Unable to open Audio Device - please retry.") self.deactivate _LOGGER.info("Audio source opened.")
pd = AubioPitchDetector(pitch_method, hop_size, pitch_frame_size, history_length) sample_limit = (history_length + 1) * hop_size for subdir, dirs, files in os.walk(folder): for file in files: if len(sys.argv) > 2 and file != sys.argv[2]: continue path = os.path.join(subdir, file) if path.endswith('.wav'): # get onset+pitches of the wav file src = create_source(path, hop_size=hop_size, verbose=False) od.create_detector(src.samplerate) pd.create_detector(src.samplerate) af = aubio.digital_filter(order=3) # 7 for A-Filter, 5 for C-Filter, 3 for biquad if filter_method == 'lowpass': if src.samplerate == 44100: af.set_biquad(.07909669122050075, .1581933824410015, .07909669122050075, -1.1486877651747005, .4650745300567037) # q=0.85, f=4700 elif src.samplerate == 48000: af.set_biquad(.06844301311767674, .13688602623535348, .06844301311767674, -1.2193255395824403, .4930975920531473) # q=0.85, f=4700 # self.filter_obj.set_biquad(0.01801576198494065, 0.0360315239698813, 0.01801576198494065, -1.4631087710168378, 0.5351718189566004) # q=0.5, f=2350 pitches = {} # onset[ms]:pitch[midi] total_read = 0 last_onset = -sample_limit while True: samples, read = src() total_read += read onset = od.process_next(samples)