def TestPyJack(self): CHANNELS=len(self.jaoutlist.curselection()) self.fs = float(jack.get_sample_rate()) print(self.jaoutlist.curselection()) for i in range(0,len(self.jaoutlist.curselection())): print(self.jaoutlist.get(self.jaoutlist.curselection()[i])) jack.activate() for i in range(0,len(self.jaoutlist.curselection())): jack.register_port('output_'+str(i), jack.IsOutput) jack.connect('measure:output_'+str(i), self.jaoutlist.get(self.jaoutlist.curselection()[i])) # Dummy Input jack.register_port('dummy_input', jack.IsInput) print(jack.get_ports()) N = jack.get_buffer_size() input = np.zeros((1,len(self.signal)),'f') output = np.array(np.tile(self.signal,(CHANNELS,1)),'f') x = 0 while x < output.shape[1] - N: try: jack.process(output[:,x:x+N], input[:,x:x+N]) x += N except jack.InputSyncError: pass except jack.OutputSyncError: pass for i in range(0,len(self.jaoutlist.curselection())): jack.unregister_port('output_'+str(i)) jack.unregister_port('dummy_input') jack.deactivate()
def MesPyJack(self): OCHANNELS=len(self.jaoutlist.curselection()) ICHANNELS=len(self.jainplist.curselection()) print(self.jainplist.curselection()) self.fs = float(jack.get_sample_rate()) jack.activate() # Register and Connect Output Ports for i in range(0,OCHANNELS): jack.register_port('output_'+str(i), jack.IsOutput) jack.connect('measure:output_'+str(i), self.jaoutlist.get(self.jaoutlist.curselection()[i])) # Register and Connect Input Ports for i in range(0,ICHANNELS): jack.register_port('input_'+str(i), jack.IsInput) jack.connect(self.jainplist.get(self.jainplist.curselection()[i]), 'measure:input_'+str(i)) N = jack.get_buffer_size() input = np.zeros((ICHANNELS,len(self.signal)),'f') output = np.array(np.tile(self.signal,(OCHANNELS,1)),'f') x = 0 while x < output.shape[1] - N: try: jack.process(output[:,x:x+N], input[:,x:x+N]) x += N except jack.InputSyncError: pass except jack.OutputSyncError: pass for i in range(0,OCHANNELS): jack.unregister_port('output_'+str(i)) for i in range(0,ICHANNELS): jack.unregister_port('input_'+str(i)) jack.deactivate() if self.rawcheck.get(): #rawfile=self.get#self.filepath.get()+os.sep+self.prefix.get()+'_RAW_'+self.counter.get()+'_AVG_'+str(int(self.siavg.get())-self.cursiavg)+'.wav' rawfile=self.getRawFilename(int(int(self.siavg.get())-self.cursiavg))#self.filepath.get()+os.sep+self.prefix.get()+'_RAW_'+self.counter.get()+'_AVG_'+str(int(self.siavg)-self.cursiavg)+'.wav' toSave = np.array(input.transpose(),dtype=('float32')) scipy.io.wavfile.write(rawfile,int(self.fs), toSave) print(rawfile+' saved') self.cursiavg-=1 #if self.impcheck.get(): self.raw.append(input) print('PyJack: append to raw') if (self.cursiavg==0) and (self.impcheck.get()): self.generateIR()
def ReadFromJack(self): #return np.random.randn(self.N) try: jack.process(self.input_slice, self.output_slice) except jack.InputSyncError: print "Input Sync Error" pass except jack.OutputSyncError: print "Output Sync Error" pass #print ".", #print(self.input_slice) #print(self.output_slice) return self.output_slice
def process(self): try: #array = tuple(empty_stream if not i==self.active else input_stream for i in range(output_n)) jack.process(numpy.concatenate(tuple(empty_stream if not i==self.active else input_stream for i in range(self.output_n))), input_stream) except jack.InputSyncError: if not args.quiet: self.errors[0] += 1 sys.stdout.write('\r\x1b[K \033[1mInput: {}\033[0m\tOutput: {}\tRatio: {}'.format(self.errors[0], self.errors[1], self.error_ratio())) sys.stdout.flush() except jack.OutputSyncError: if not args.quiet: self.errors[1] += 1 sys.stdout.write('\r\x1b[K Input: {}\t\033[1mOutput: {}\033[0m\tRatio: {}'.format(self.errors[0], self.errors[1], self.error_ratio())) sys.stdout.flush() return True
def __PlayAndRecord(self, playbuffer, errormessage=""): """ A wrapper for jack.process. @param playbuffer: a numpy array with samples that shall be played @param errormessage: an optional message that will be appended to the standard message, when a jack-Error has occured @retval : a buffer with the recorded samples """ recorded = numpy.zeros(shape=(self._recordchannels, self.__buffer_size), dtype=numpy.float32) try: jack.process(playbuffer, recorded) except jack.InputSyncError: pass # print("InputSyncError %s" % errormessage) except jack.OutputSyncError: print("OutputSyncError %s" % errormessage) return recorded
def ReadFromJack(linput_slice=None, loutput_slice=None): if linput_slice == None and loutput_slice == None: global input_slice, output_slice else: input_slice = linput_slice output_slice = loutput_slice try: jack.process(input_slice, output_slice) except jack.InputSyncError: print "Input Sync Error" # self.update_time += 20 # print("setting update time to %d" %(self.update_time)) pass except jack.OutputSyncError: print "Output Sync Error" pass
def process_multi(self): try: jack.process(numpy.concatenate(tuple(empty_stream if not self.output_ports[i] else input_stream for i in range(self.output_n))), input_stream) except jack.InputSyncError: self.errors[0] += 1 if args.statusbar: self.status_update(0) if not args.quiet: sys.stdout.write('\r\x1b[K \033[1mInput: {}\033[0m\tOutput: {}\tRatio: {}'.format(self.errors[0], self.errors[1], self.error_ratio())) sys.stdout.flush() except jack.OutputSyncError: self.errors[1] += 1 if args.statusbar: self.status_update(1) if not args.quiet: sys.stdout.write('\r\x1b[K Input: {}\t\033[1mOutput: {}\033[0m\tRatio: {}'.format(self.errors[0], self.errors[1], self.error_ratio())) sys.stdout.flush() return True
def run(self): while self.nonstop_event.isSet(): try: jack.process(self.output, self.capture) # Add a Lock self.output = self.capture.copy() self.counter[0] += 1 time.sleep(self.sleep) except jack.InputSyncError: print >> sys.stderr, "Input Sync Error, samples lost" except jack.OutputSyncError: print >> sys.stderr, "Output Sync" # Workarround to put output buffer to zero. If not for some reason # jackd will constantly output the last buffer, making noise self.output = self.output*0 jack.process(self.output, self.capture) time.sleep(0.2) # "Waiting" the jack thread to sync. jack.deactivate() jack.detach() self.nonstop_event.set()
def start(self): import jack jack.attach("NoteRecogniser Recorder") jack.register_port("in_1", jack.IsInput) jack.activate() try: jack.connect("system:capture_1", "NoteRecogniser Recorder:in_1") jack.connect("system:capture_2", "NoteRecogniser Recorder:in_1") except err: print("Unable to connect to system:capture") buffer_size = jack.get_buffer_size() sample_rate = float(jack.get_sample_rate()) print "Buffer Size:", buffer_size, "Sample Rate:", sample_rate output = scipy.zeros((1, buffer_size), 'f') while True: try: input = scipy.zeros((1, buffer_size), 'f') jack.process(output, input) #print len(input) fft = numpy.fft.rfft(input[0]) fft = map( lambda c: math.sqrt(c.real * c.real + c.imag * c.imag), fft) #print(len(fft)) dominant = reduce(lambda y, x: x if x[1] > y[1] else y, zip(range(len(fft)), fft), [0, 0]) print dominant except jack.InputSyncError: print "Input Sync Error" pass except jack.OutputSyncError: print "Output Sync Error" pass
def play(self, audiodata): if self.output == 'jack': if self.jackSampleRate != audiodata.sampleRate: raise Exception('Sample rate of audio different from sample rate of Jack audio server') n = self.n input = numpy.zeros((1, n), 'f').astype('f') i = 0 # converting from int16 to jack float output = audiodata.data.astype('f').T / 32768.0 while i < output.shape[1] - n: try: jack.process(output[:,i:i+n], input) i += n except jack.InputSyncError: pass except jack.OutputSyncError: print "output lost sync while playing at " + str(i/float(audiodata.sampleRate)) + " seconds" pass self._reset_jack() else: # use pyao dev = ao.AudioDevice(self.output, channels = self.numChannels, rate = audiodata.sampleRate) dev.play(audiodata.data, len(audiodata.data))
def start(self): import jack jack.attach("NoteRecogniser Recorder") jack.register_port("in_1", jack.IsInput) jack.activate() try: jack.connect("system:capture_1", "NoteRecogniser Recorder:in_1") jack.connect("system:capture_2", "NoteRecogniser Recorder:in_1") except err: print ("Unable to connect to system:capture") buffer_size = jack.get_buffer_size() sample_rate = float(jack.get_sample_rate()) print "Buffer Size:", buffer_size, "Sample Rate:", sample_rate output = scipy.zeros((1,buffer_size), 'f') while True: try: input = scipy.zeros((1,buffer_size), 'f') jack.process(output, input) #print len(input) fft = numpy.fft.rfft(input[0]) fft = map(lambda c : math.sqrt(c.real*c.real + c.imag*c.imag), fft) #print(len(fft)) dominant = reduce(lambda y,x: x if x[1] > y[1] else y, zip(range(len(fft)), fft), [0,0]) print dominant except jack.InputSyncError: print "Input Sync Error" pass except jack.OutputSyncError: print "Output Sync Error" pass
smooth_release_frames = time_to_frames(float(arguments["--release"]) / 1000) smooth_release_coefficient = AttackReleaseFilter.get_coefficient(smooth_release_frames) volume_filter = VolumeFollowFilter( envelope_cutoff_frames, emphasis_cutoff_frames, emphasis_opacity, smooth_attack_coefficient, smooth_release_coefficient ) # Begin processing audio jack.activate() try: while True: try: jack.process(jack_output, jack_input) input_buffer = jack_input[0].tolist() for i in xrange(buffer_size): output_buffer[i] = volume_filter.process(input_buffer[i]) except jack.InputSyncError, e: print "JACK: we couldn't process data in time." count = map_to_leds(output_buffer[0], map_options) # TODO: respect -f send_leds(client, leds, count) except KeyboardInterrupt, e: pass # Close everything jack.deactivate() jack.detach() sock.close()
N = jack.get_buffer_size() Sr = float(jack.get_sample_rate()) print "Buffer Size:", N, "Sample Rate:", Sr sec = 3.0 capture = numpy.zeros((2,int(Sr*sec)), 'f') dummy = numpy.zeros((2,0), 'f') #time.sleep(1) print "Capturing audio..." i = 0 while i < capture.shape[1] - N: try: jack.process(dummy, capture[:,i:i+N]) i += N except jack.InputSyncError: print "Input Sync" pass except jack.OutputSyncError: print "Output Sync" pass print ".", print "Playing back..." jack.deactivate() jack.unregister_port("in_1") jack.unregister_port("in_2")
fftsize = 10 fft = scipy.zeros(fftsize) fft = scipy.fft(data, fftsize) fft = fft[:len(fft) / 2] fft = abs(fft) fft *= 0.05 v.display(fft) while True: i = 0 capture = scipy.zeros((1, int(sample_rate * sec)), 'f') while i < capture.shape[1] - buffer_size: try: jack.process(output, capture[:, i:i + buffer_size]) i += buffer_size except jack.InputSyncError: print "Input Sync" pass except jack.OutputSyncError: print "Output Sync" pass # print len(capture[0]) parse(capture[0]) jack.deactivate() jack.detach() #inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE)
def start_recording_jack(event_queue, control_queue, pcm, birdname, channel, rate, format, chunk, silence_limit, prev_audio_time, min_dur, max_dur, threshold, outdir): stream = None print birdname if uname == "Linux": channel = str(channel) establish_connection(pcm, channel) chunk = jack.get_buffer_size() print "Buffer Size:", chunk, "Sample Rate:", rate cur_data = np.zeros((1, chunk), 'f') dummy = np.zeros((1, 0), 'f') else: pass print "AudioRecorder started (listening...)" audio2send = [] rel = rate / chunk slid_win = deque(maxlen=silence_limit * rel) #amplitude threshold running buffer slid_win_short = Ringbuffer(0.5 * rate) #freq calc running buffer prev_audio = Ringbuffer(prev_audio_time * rate) #prepend audio running buffer started = False control_force_record = True control_force_record_just_stopped = False if uname == "Linux": try: jack.process(dummy, cur_data) except jack.InputSyncError: pass else: pass slid_win.append(get_audio_power_jack(cur_data[0, :])) slid_win_short.extend(cur_data[0, :]) while True: ## check whether any events are in queue and if so change control_force_record accordingly command = None control_force_record_just_stopped = False if not control_queue.empty(): command = control_queue.get(block=True) if control_force_record: if command == "start": pass elif command == "stop": control_force_record = False #control_force_record_just_stopped = True control_force_record_just_stopped = False #temporary fix pass else: if command == "start": control_force_record = True elif command == "stop": pass pass #if len(slid_win)>0: # print max(slid_win) #uncomment if you want to print intensity values if uname == "Linux": try: jack.process(dummy, cur_data) except jack.InputSyncError: pass else: pass try: slid_win.append(get_audio_power_jack(cur_data[0, :])) slid_win_short.extend(cur_data[0, :]) except audioop.error: print "invalid number of blocks for threshold calculation, but continuing" if (sum([x > threshold for x in slid_win]) > 0) and control_force_record: if (not started): event_queue.put((time.time(), "Audio Recording Started", slid_win_short.get())) prev_audio_time_emperical = float(len(prev_audio)) / rel recording_start_time = time.time() - prev_audio_time_emperical sys.stdout.flush() started = True audio2send = np.array(cur_data[0, :]) else: audio2send = np.append(audio2send, cur_data[0, :]) event_queue.put((time.time(), 'audio_threshold_crossing', slid_win_short.get())) #audio2send.append(cur_data) elif (started is True and np.shape(audio2send)[0] > min_dur * rate and np.shape(audio2send)[0] < max_dur * rate or control_force_record_just_stopped): today = datetime.date.today().isoformat() outdir_date = "/".join([outdir, today]) if not os.path.exists(outdir_date): os.makedirs(outdir_date) filename = save_audio_jack(np.append(prev_audio.get(), audio2send), recording_start_time, outdir_date, rate) event_queue.put((time.time(), "Audio File Saved: %s" % filename)) event_queue.put((time.time(), "stop_triggered_audio")) event_queue.put((time.time(), "audio_saved")) started = False slid_win = deque(maxlen=silence_limit * rel) #prev_audio = deque(maxlen=prev_audio_time * rel) prev_audio = Ringbuffer(prev_audio_time * rate) #prepend audio running buffer prev_audio.extend(audio2send) event_queue.put((time.time(), "Listening")) audio2send = np.array(cur_data[0, :]) elif (started is True): event_queue.put((time.time(), "stop_triggered_audio")) event_queue.put( (time.time(), "Duration Criteria not met, listening")) started = False slid_win = deque(maxlen=silence_limit * rel) #prev_audio = deque(maxlen=prev_audio_time * rel) prev_audio = Ringbuffer(prev_audio_time * rate) #prepend audio running buffer prev_audio.extend(audio2send) audio2send = np.array(cur_data[0, :]) #audio2send=[] else: prev_audio.extend(cur_data[0, :]) #prev_audio.append(cur_data) else: #print "done recording" jack.deactivate() jack.detach() return
Sr = float(jack.get_sample_rate()) print "Buffer Size:", N, "Sample Rate:", Sr sec = 3.0 capture = numpy.zeros((2, int(Sr * sec)), 'f') input = numpy.zeros((2, N), 'f') output = numpy.zeros((2, N), 'f') #time.sleep(1) print "Capturing audio..." i = 0 while i < capture.shape[1] - N: try: jack.process(output, capture[:, i:i + N]) i += N except jack.InputSyncError: print "Input Sync" pass except jack.OutputSyncError: print "Output Sync" pass print ".", print "\nPlaying back..." i = 0 iS = 0 oS = 0 while i < capture.shape[1] - N:
def parse(data): fftsize = 10 fft = scipy.zeros(fftsize) fft = scipy.fft(data,fftsize) fft = fft[:len(fft) / 2] fft = abs(fft) fft *= 0.05 v.display(fft) while True: i = 0 capture = scipy.zeros((1,int(sample_rate*sec)), 'f') while i < capture.shape[1] - buffer_size: try: jack.process(output, capture[:,i:i+buffer_size]) i += buffer_size except jack.InputSyncError: print "Input Sync" pass except jack.OutputSyncError: print "Output Sync" pass # print len(capture[0]) parse(capture[0]) jack.deactivate() jack.detach()
def process(self, output_buffer, input_buffer): try: jack.process(output_buffer, input_buffer) except jack.InputSyncError: print("InputSyncError")
# make this general case. # when MIDI message commes in, assign that message to the space # when the sound is near to that, play that same message pts = {} pts[0] = array([]) pts[0].resize(513) lastnote = 0 bufnum = 0 while True : try: # for j in range(window/N-1) : # input[:,j*N] = input[:,(j+1)*N] jack.process(output, input[:,-N:]) x = rfft(input[0]*hamming(window)) x = array(map(lambda c : math.sqrt(c.real*c.real + c.imag*c.imag), x)) dists = [(i, linalg.norm(x-pt)) for i, pt in pts.iteritems()] _, mini = findminp(dists) # if lastnote != mini : midiout.sendMessage(144, mini, 0) lastnote = mini if mini != 0 : # TODO: use RMS volume of input signal as value here midiout.sendMessage(144, mini, 120) print mini
Sr = float(jack.get_sample_rate()) print "Buffer Size:", N, "Sample Rate:", Sr sec = 3.0 capture = numpy.zeros((2,int(Sr*sec)), 'f') input = numpy.zeros((2,N), 'f') output = numpy.zeros((2,N), 'f') #time.sleep(1) print "Capturing audio..." i = 0 while i < capture.shape[1] - N: try: jack.process(output, capture[:,i:i+N]) i += N except jack.InputSyncError: print "Input Sync" pass except jack.OutputSyncError: print "Output Sync" pass print ".", print "Playing back..." i = 0 while i < capture.shape[1] - N: try: jack.process(capture[:,i:i+N], input)
N = jack.get_buffer_size() Sr = float(jack.get_sample_rate()) print "Buffer Size:", N, "Sample Rate:", Sr sec = 3.0 capture = numpy.zeros((2, int(Sr * sec)), 'f') dummy = numpy.zeros((2, 0), 'f') #time.sleep(1) print "Capturing audio..." i = 0 while i < capture.shape[1] - N: try: jack.process(dummy, capture[:, i:i + N]) i += N except jack.InputSyncError: print "Input Sync" pass except jack.OutputSyncError: print "Output Sync" pass print ".", print "Playing back..." jack.deactivate() jack.unregister_port("in_1") jack.unregister_port("in_2")
headphones = numpy.zeros((channels,bufsize), 'f') microphones = numpy.zeros((channels,bufsize), 'f') # Testing debug = 0 sock = None #new = conversation.conversation() #new.forceinvite(telephones[2]) #conversations.append(new) ringposition = 0 nextringposition = ringposition while(True): # Main Loop if (debug): print "Process in/out with jack" try: jack.process(headphones, microphones) except jack.InputSyncError, e: print repr(e) except jack.OutputSyncError, e: print repr(e) if (debug): print "Splitting" micsplit = numpy.vsplit(microphones,channels) out = list() for x in range(channels): out.append([numpy.zeros((1,bufsize),'f')]) if (debug): print "Run telephone sounds" pamode = False for telephone in telephones:
try: while True: if AUDIO_MODE == 'alsa': rms = 0.0 frame = pipe.read(framesize * 2) # 2 bytes per sample (16-bit) if len(frame) == framesize * 2: for sample in struct.unpack('<' + framesize * 'h', frame): rms += (sample / 32768.0) ** 2 rms = math.sqrt(rms / framesize) else: print 'Error in audio subprocess, restarting...' pipe.close() pipe = os.popen(command, 'r', 0) elif AUDIO_MODE == 'jack': try: jack.process(output_array, input_array) except (jack.InputSyncError, jack.OutputSyncError): print 'Jack out of sync' rms = math.sqrt(numpy.sum(numpy.power(input_array[0], 2)) / framesize) if rms > 0: volume = math.log(rms, 1.15) else: volume = SILENCE if volume > maxvolume: maxvolume = volume if time.time() >= time_update: scaled = (maxvolume - scale_min) / ( scale_max - scale_min) * TARGET_HEIGHT scaled = min(scaled, 1.3 * TARGET_HEIGHT, 254) if scaled < 0:
hues = array([(log2(F) - log2(440)) % 1 for F in freqs]) hue_order = array(sorted(enumerate(hues[1:], 1), key=lambda f: f[1]), "i").T[0] freq_rgb = array([hue_to_rgb(h) for h in hues]) capture = np.zeros((1, buff), "f") dummy = np.zeros((0, 0), "f") pygame.init() size = (1024, 32) window = pygame.display.set_mode(size) ffact = size[0] / float(len(freqs)) while True: try: jack.process(dummy, capture) except jack.InputSyncError: print "Input Sync" transformed = np.fft.rfft(capture[0][1:]) # pygame.draw.rect(window, pygame.Color(0,0,0), (0,0,size[0],size[1])) pygame.draw.rect(window, pygame.Color(0, 0, 0), (0, 0, size[0], size[1])) edge = 0 for index in hue_order: colour = pygame.Color(*[int(c) for c in 255 * freq_rgb[index]]) amp = transformed[index] width = amp + 1 pygame.draw.rect(window, colour, (edge, 0, width, size[1])) edge += width
def read(self): jack.process(self.output, self.input) #i16s = self.input * 2**16 i16s = [int(n * 2**16) for n in self.input[0]] return self.buffer_size, i16s
smooth_release_coefficient = AttackReleaseFilter.get_coefficient( smooth_release_frames) volume_filter = VolumeFollowFilter(envelope_cutoff_frames, emphasis_cutoff_frames, emphasis_opacity, smooth_attack_coefficient, smooth_release_coefficient) # Begin processing audio jack.activate() try: while True: try: jack.process(jack_output, jack_input) input_buffer = jack_input[0].tolist() for i in xrange(buffer_size): output_buffer[i] = volume_filter.process(input_buffer[i]) except jack.InputSyncError, e: print "JACK: we couldn't process data in time." count = map_to_leds(output_buffer[0], map_options) # TODO: respect -f send_leds(client, leds, count) except KeyboardInterrupt, e: pass # Close everything jack.deactivate() jack.detach()
underruns = 0 overruns = 0 g = dB2g(gaindB) while True: try: # amplificamos: ao = ai * g omax = np.max(ao) # warnings if omax > 1.0: op = str(round(20*np.log10(omax), 1)) + " dB" print "out_peak: " + op # procesamos contra el thread real time de jackd jack.process(ao, ai) except jack.InputSyncError: underruns += 1 print "input sync warnings: " + str(underruns) except jack.OutputSyncError: overruns += 1 print "output sync warnings: " + str(overruns) #xruns = underruns + overruns #if xruns > 100: # print "esto se sale de madre" # break #jack.deactivate()
def _reset_jack(self): # weird noise if we don't process an empty buffer # must look into pyjack to see what's going on input = numpy.zeros((1, self.n), 'f').astype('f') output = numpy.zeros((self.numChannels, self.n), 'f').astype('f') jack.process(output, input)
if raster[r]: start=N-(i+N-(clicks_played*samples_to_next_click)) play_click=True output_start=0 clicks_played+=1 if (play_click): ende=output_start+N-start buffer_ende=N if ende>=len(output): ende=len(output) buffer_ende=ende-output_start play_click=False out_buffer[0,start:buffer_ende]=output[output_start:ende] output_start=ende+1 start=0 jack.process(out_buffer, input) #output_start+=float(N) i += N except jack.InputSyncError: pass except jack.OutputSyncError: pass except KeyboardInterrupt: print('exeting...') finally: jack.deactivate() jack.detach() print(output.shape) #try:
jack.attach("testtone") jack.register_port("in_1", jack.IsInput) jack.register_port("out_1", jack.IsOutput) jack.activate() jack.connect("testtone:out_1", "alsa_pcm:playback_1") N = jack.get_buffer_size() Sr = float(jack.get_sample_rate()) print "Buffer Size:", N, "Sample Rate:", Sr sec = 3.0 input = numpy.zeros((1,N), 'f') output = numpy.reshape( numpy.sin( 2*numpy.pi*440.0 * (numpy.arange(0, sec, 1.0/(Sr), 'f')[0:int(Sr*sec)]) ), (1, Sr*sec)).astype('f') i = 0 while i < output.shape[1] - N: try: jack.process(output[:,i:i+N], input) i += N except jack.InputSyncError: pass except jack.OutputSyncError: pass jack.deactivate() jack.detach()
# make this general case. # when MIDI message commes in, assign that message to the space # when the sound is near to that, play that same message pts = {} pts[0] = array([]) pts[0].resize(513) lastnote = 0 bufnum = 0 while True: try: # for j in range(window/N-1) : # input[:,j*N] = input[:,(j+1)*N] jack.process(output, input[:, -N:]) x = rfft(input[0] * hamming(window)) x = array( map(lambda c: math.sqrt(c.real * c.real + c.imag * c.imag), x)) dists = [(i, linalg.norm(x - pt)) for i, pt in pts.iteritems()] _, mini = findminp(dists) # if lastnote != mini : midiout.sendMessage(144, mini, 0) lastnote = mini if mini != 0: # TODO: use RMS volume of input signal as value here midiout.sendMessage(144, mini, 120) print mini