Beispiel #1
0
 def stop(self):
     self.running = False
     self.event_queue.put(1)
     if self.audio_server == 'jack':
         self.jack_client_process.kill()
         jack.deactivate()
         jack.detach()
Beispiel #2
0
	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()
Beispiel #3
0
 def Delete(self):
     """
     Shuts down the jack connection and prepares the instance for garbage collection.
     """
     if not self.__deleted:
         jack.deactivate()
         jack.detach()
         sumpf.destroy_connectors(self)
         BaseIO.Delete(self)
         self.__deleted = True
Beispiel #4
0
	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()
Beispiel #5
0
 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()
Beispiel #6
0
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()
Beispiel #7
0
 def cleanup(self):
     jack.deactivate()
     jack.detach()
     self.player.set_state(gst.STATE_NULL)
     del(self.player)
Beispiel #8
0
 def quit(self, *args):
     jack.deactivate()
     jack.detach()
     gtk.main_quit()
     print ''
Beispiel #9
0
 def close(self):
     jack.detach()
     jack.deactivate()
Beispiel #10
0
def jack_cleanup():
    jack.deactivate()
    jack.detach()
    print ("jscope detached from jack")
Beispiel #11
0
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