def listen(self): p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=var.CHANNELS, rate=var.RATE, input=True, frames_per_buffer=var.CHUNK) print("* recording * ") data = stream.read(var.CHUNK) i = 0 last_match = -1 challenger = -1 successive_challenge = 0 while(True): try: data = stream.read(var.CHUNK) except IOError: pass i += 1 if i%2 == 0 : data_fft = da.normalize(da.getFft(data, var.RATE)) best_match, distance_to_best_match = self.match(data_fft) if last_match == -1 : last_match = best_match print "I got " + best_match.name + " with an error of " + str(distance_to_best_match) else : if last_match != best_match : # distance_to_last_match = da.distance(data_fft, last_match.chord_fft) if best_match == challenger or challenger == -1 : successive_challenge += 1 if successive_challenge > 3 : print "I got " + best_match.name + " with an error of " + str(distance_to_best_match) last_match = best_match challenger = -1 successive_challenge = 0 else : # print "o" pass else : # print "x" challenger = best_match successive_challenge = 0 else : # print "." challenger = -1 successive_challenge = 0 print("* done recording") stream.stop_stream() stream.close() p.terminate()
def learn_from_wave_file(self, file_path) : print "Learning for "+ self.name wf = wave.open(file_path, 'rb') dictionaries = [] p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(var.CHUNK) while data != '': dictionaries.append(da.normalize(da.getFft(data, var.RATE))) data = wf.readframes(var.CHUNK) stream.stop_stream() stream.close() # Average the dictionary mean_dictionnary = da.average_dictionary(dictionaries) print "Done Learning" threshold = 0 ; for fft_data in dictionaries : threshold += da.distance(fft_data, mean_dictionnary) threshold /= len(dictionaries) print "Done setting the threshold at " + str(threshold) real_list = [] for fft_data in dictionaries : if da.distance(fft_data, mean_dictionnary) < threshold : real_list.append(fft_data) new_mean = da.average_dictionary(real_list) print "Done filtering" print "Distance between the new and old means is " + str(da.distance(mean_dictionnary, new_mean)) threshold = 0 ; for fft_data in real_list : threshold += da.distance(fft_data, new_mean) threshold /= len(real_list) print "Done resetting the threshold at " + str(threshold) print len(real_list) self.chord_fft = new_mean self.threshold = threshold