Esempio n. 1
0
    def __init__(self):
        jack.attach("stream_grapher")
        jack.register_port("in_1", jack.IsInput)
        jack.register_port("in_2", jack.IsInput)
        jack.register_port("out_1", jack.IsOutput)
        jack.register_port("out_2", jack.IsOutput)

        jack.activate()
        try:
            jack.connect("system:capture_1", "stream_grapher:in_1")
            jack.connect("system:capture_2", "stream_grapher:in_2")
            jack.connect("stream_grapher:out_1", "system:playback_1")
            jack.connect("stream_grapher:out_2", "system:playback_2")
        except jack.UsageError:
            pass
        
        buff_size = jack.get_buffer_size()
        if buff_size < 1024:
            print >> sys.stderr, "Jack buffer size is %d. If you have sync problems try a buff size >= 1024." % (buff_size, )

        self.buff_size = jack.get_buffer_size()
        sample_rate = jack.get_sample_rate()

        Backend.__init__(self, ports=2, sample_rate=sample_rate)
        self.capture = numpy.zeros((2, self.buff_size), 'f')
        self.output = numpy.zeros((2, self.buff_size), 'f')

        self.counter = [0]
        self.last_counter = 0

        # Time to sleep between calls to jack.process
        # R should be at least 1.0
        # To never get InputSyncErrors R should be like 2.0 or higher
        R = 1.2
        self.sleep = self.buff_size / float(self.sample_rate) / R
Esempio n. 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()
Esempio n. 3
0
 def _Record(self):
     """
     Starts the playback and recording process.
     """
     self.__buffer_size = jack.get_buffer_size()
     playback = []
     record = []
     record_length = self._record_length
     if record_length == JackIO.SAME_AS_PLAYBACK or record_length == JackIO.WAIT_FOR_STOP:
         record_length = len(self._playback)
     # cut the playback signal in chunks of the size of the buffer and write it into a list of numpy arrays
     b = 0
     while b < record_length:
         playbuffer = numpy.zeros(shape=(self._playbackchannels, self.__buffer_size), dtype=numpy.float32)
         for c in range(self._playbackchannels):
             if c < len(self._playback.GetChannels()):
                 for s in range(self.__buffer_size):
                     if b + s < len(self._playback):
                         playbuffer[c][s] = self._playback.GetChannels()[c][b + s]
         playback.append(playbuffer)
         b += self.__buffer_size
     for i in range(self.__periods):
         playbuffer = numpy.zeros(shape=(self._playbackchannels, self.__buffer_size), dtype=numpy.float32)
         playback.append(playbuffer)
     # play empty buffer to avoid InputSyncErrors
     playbuffer = numpy.zeros(shape=(self._playbackchannels, self.__buffer_size), dtype=numpy.float32)
     self.__PlayAndRecord(playbuffer, "while not recording")
     # play and record with playback signal
     for b in playback:
         if not self._recording:
             break
         recorded = self.__PlayAndRecord(b)
         record.append(recorded)
     # play and record until the Stop method is called
     if self._record_length == JackIO.WAIT_FOR_STOP:
         while self._recording:
             playbuffer = numpy.zeros(shape=(self._recordchannels, self.__buffer_size), dtype=numpy.float32)
             recorded = self.__PlayAndRecord(playbuffer)
             record.append(recorded)
         record_length = (len(record) - self.__periods) * self.__buffer_size
     # play empty buffer to avoid crackling noises at playback stop
     playbuffer = numpy.zeros(shape=(self._playbackchannels, self.__buffer_size), dtype=numpy.float32)
     self.__PlayAndRecord(playbuffer, "while not recording")
     # create output Signal
     channels = []
     for c in range(self._recordchannels):
         channel = []
         for b in range(self.__periods, len(record)):
             for s in record[b][c]:
                 channel.append(s)
         channels.append(tuple(channel[0:record_length]))
     self._record = sumpf.Signal(channels=channels, samplingrate=self.GetSamplingRate(), labels=self._GetLabels())
Esempio n. 4
0
        def __init__(self, url):
            log.info("Opening JACK input")
            jack.attach("Noter Virtual Keyboard")
            self.rate = jack.get_sample_rate()
            jack.activate()
            jack.register_port("Input 1", jack.IsInput)
            jack.register_port("Input 2", jack.IsInput)
            jack.connect("system:capture_1", "Noter Virtual Keyboard:Input 1")
            jack.connect("system:capture_2", "Noter Virtual Keyboard:Input 2")

            self.buffer_size = jack.get_buffer_size()
            self.input = numpy.zeros((2, self.buffer_size), 'f')
            self.output = numpy.zeros((2, self.buffer_size), 'f')
Esempio n. 5
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()
Esempio n. 6
0
    def __init__(self, nscopes, subsamp_factor, length, zoom):
        self.scopes = range(nscopes)
        jack.attach("jscope")
        print(jack.get_ports())
        for i in self.scopes:
            jack.register_port("in_%d" % (i), jack.IsInput)
        jack.activate()
        print jack.get_ports()
        #jack.connect(jack.get_ports()[-2], "jscope:in_1")

        # CONSTANTS
        self.N = jack.get_buffer_size()
        self.Sr = float(jack.get_sample_rate())
        self.plotlength = length  #  plot length in seconds
        self.abscissa = -np.arange(self.Sr * self.plotlength) / self.Sr

        self.input_slice = np.zeros((nscopes, self.N), dtype='f')
        self.output_slice = self.input_slice.copy()

        self.fig = Figure()
        self.subsamp_factor = subsamp_factor
        self.ax = []
        self.plot_data = []
        self.l_plot_data = []
        self.input_ring = []
        self.output_ring = []
        for i in self.scopes:
            self.ax.append(self.fig.add_subplot(nscopes, 1, i + 1))
            self.ax[i].set_ylim(-zoom, zoom)
            self.plot_data.append([])
            foo, = self.ax[i].plot([], self.plot_data[i])
            self.l_plot_data.append(foo)
            self.input_ring.append(RingBuffer(self.abscissa.size))
            self.output_ring.append(RingBuffer(self.abscissa.size))
            self.ax[i].set_xlim(self.abscissa[0], self.abscissa[-1])
            self.ax[i].grid()

        FigureCanvas.__init__(self, self.fig)
        self.fig.canvas.draw()

        self.timerEvent(None)
        self.timer = self.startTimer(0)
Esempio n. 7
0
    def __init__(self, nscopes, subsamp_factor, length, zoom):
        self.scopes = range(nscopes)
        jack.attach("jscope")
        print(jack.get_ports())
        for i in self.scopes:
            jack.register_port("in_%d" %(i), jack.IsInput)
        jack.activate()
        print jack.get_ports()
        #jack.connect(jack.get_ports()[-2], "jscope:in_1")

        # CONSTANTS
        self.N = jack.get_buffer_size()
        self.Sr = float(jack.get_sample_rate())
        self.plotlength = length #  plot length in seconds
        self.abscissa = -np.arange(self.Sr*self.plotlength) / self.Sr
        
        self.input_slice = np.zeros((nscopes, self.N), dtype='f')
        self.output_slice = self.input_slice.copy()

        self.fig = Figure()
        self.subsamp_factor = subsamp_factor
        self.ax = []
        self.plot_data = []
        self.l_plot_data = []
        self.input_ring = []
        self.output_ring = []
        for i in self.scopes:
            self.ax.append(self.fig.add_subplot(nscopes, 1, i+1))
            self.ax[i].set_ylim(-zoom, zoom)
            self.plot_data.append([])
            foo, = self.ax[i].plot([], self.plot_data[i])
            self.l_plot_data.append(foo)
            self.input_ring.append(RingBuffer(self.abscissa.size))
            self.output_ring.append(RingBuffer(self.abscissa.size))
            self.ax[i].set_xlim(self.abscissa[0], self.abscissa[-1])
            self.ax[i].grid()

        FigureCanvas.__init__(self, self.fig)
        self.fig.canvas.draw()

        self.timerEvent(None)
        self.timer = self.startTimer(0)
Esempio n. 8
0
    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
Esempio n. 9
0
 def __init__(self, output='jack', numChannels = 2):
     self.numChannels = numChannels
     self.output = output
     if output == 'jack':
         # use pyjack
         import jack
         try:
             jack.get_client_name()
         except jack.NotConnectedError:
             jack.attach('remix')
             # not registering an input port makes the output sync
             # consistently break after processing 2 buffers
             # - bug in pyjack?
             jack.register_port("in_1", jack.IsInput)
             for i in range(0, self.numChannels):
                 jack.register_port("out_" + str(i+1), jack.IsOutput)
             jack.activate()
             for i in range(0, self.numChannels):
                 jack.connect("remix:out_" + str(i+1), "alsa_pcm:playback_" + str(i+1))
         self.n = jack.get_buffer_size()
         self.jackSampleRate = float(jack.get_sample_rate())
         # loosing a buffer, here, see below
         self._reset_jack()
Esempio n. 10
0
    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
Esempio n. 11
0
# Plays a 440.0 Hz test tone for 3 seconds to alsa_pcm:playback_1.
#
# Copyright 2003, Andrew W. Schmeder
# This source code is released under the terms of the GNU Public License.
# See LICENSE for the full text of these terms.

import numpy
import jack

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
Esempio n. 12
0
 def __GetNumberOfPeriods(self):
     """
     Querys the number of buffer periods of the jack server.
     Since neither the Jack latency functions nor the querying of the number
     of buffer periods are available in PyJack, this method is a dirty workaround
     to obtain this number.
     @retval : The number of buffer periods of the Jack server
     """
     for p in self.GetCapturePorts():
         if jack.get_port_flags(p) & jack.IsPhysical:
             return int(subprocess.check_output(["jack_lsp", "-l", p]).split("\n")[1].strip().split(" ")[-2]) / jack.get_buffer_size()
     return 2
Esempio n. 13
0
net.send('VU')
time_update = time.time()
time_random = time_update

if AUDIO_MODE == 'alsa':
    framesize = 1024
    rate = 22050
    pipe = os.popen('arecord -N -c 1 -r %d -f S16_LE' % (rate,), 'r', 0)
elif AUDIO_MODE == 'jack':
    jack.attach('VU-Meter')
    jack.register_port('in_1', jack.IsInput)
    jack.register_port('out_1', jack.IsOutput)
    jack.activate()
    # jack.connect('alsa_pcm:capture_1', 'VU-Meter:in_1')
    jack.connect('system:capture_1', 'VU-Meter:in_1')
    framesize = jack.get_buffer_size()
    rate = jack.get_sample_rate()
    input_array = numpy.zeros((1, framesize), 'f')
    output_array = numpy.zeros((1, framesize), 'f')

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...'
Esempio n. 14
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