コード例 #1
0
ファイル: moseq.py プロジェクト: alexklaeser/moseq
def loop():
    '''Main loop function, calls processing sub-functions.'''
    global _jackRunning

    # compute the current tick
    interval = 60.0 / tempo / 2  # call the loop twice per beat (for blinking)
    transportTime = float(
        jack.get_current_transport_frame()) / jack.get_sample_rate()
    tickCount = math.floor(transportTime / interval)

    if tickCount > 0 and not _jackRunning:
        print 'jack is up and running... starting monome sequencer'
        _jackRunning = True

    if jack.get_transport_state() != jack.TransportRolling:
        # jack is stopped... stop processing here, as well
        if tickCount == 0 and _jackRunning:
            print 'jack transport has been stopped... waiting for jack to be restarted'
            _jackRunning = False
            mon.led_all(0)
            for i, itrack in tracks.iteritems():
                itrack.clear()
        Timer(0.1, loop).start()
        return

    # processing
    readEvents(tickCount)
    beat(tickCount)

    # see when the loop needs to be called the next time
    transportTime = float(
        jack.get_current_transport_frame()) / jack.get_sample_rate()
    waitTime = (tickCount + 1) * interval - transportTime
    Timer(waitTime, loop).start()
コード例 #2
0
ファイル: moseq.py プロジェクト: alexklaeser/moseq
def loop():
    """Main loop function, calls processing sub-functions."""
    global _jackRunning

    # compute the current tick
    interval = 60.0 / tempo / 2  # call the loop twice per beat (for blinking)
    transportTime = float(jack.get_current_transport_frame()) / jack.get_sample_rate()
    tickCount = math.floor(transportTime / interval)

    if tickCount > 0 and not _jackRunning:
        print "jack is up and running... starting monome sequencer"
        _jackRunning = True

    if jack.get_transport_state() != jack.TransportRolling:
        # jack is stopped... stop processing here, as well
        if tickCount == 0 and _jackRunning:
            print "jack transport has been stopped... waiting for jack to be restarted"
            _jackRunning = False
            mon.led_all(0)
            for i, itrack in tracks.iteritems():
                itrack.clear()
        Timer(0.1, loop).start()
        return

        # processing
    readEvents(tickCount)
    beat(tickCount)

    # see when the loop needs to be called the next time
    transportTime = float(jack.get_current_transport_frame()) / jack.get_sample_rate()
    waitTime = (tickCount + 1) * interval - transportTime
    Timer(waitTime, loop).start()
コード例 #3
0
    def refreshUi(self):
        state = jack.get_transport_state()
        frame = jack.get_current_transport_frame()
        rate = jack.get_sample_rate()

        # Jack State
        if (state == 0):
            self.l_state.setText("Stopped")
            self.b_play.setChecked(False)
        elif (state == 1):
            self.l_state.setText("Rolling")
            self.b_play.setChecked(True)
        elif (state == 3):
            self.l_state.setText("Starting")
        else:
            self.l_state.setText("Unknown (%i)" % state)

        # Current Time
        time = frame / rate
        secs = time % 60
        mins = (time / 60) % 60
        hrs = (time / 3600) % 60
        secH = minH = hrsH = ""
        if secs < 10: secH = "0"
        if mins < 10: minH = "0"
        if hrs < 10: hrsH = "0"
        self.l_time.setText(hrsH + str(hrs) + ":" + minH + str(mins) + ":" +
                            secH + str(secs))

        # Current Frame
        self.l_frame.setText(str(frame))
コード例 #4
0
ファイル: mes.py プロジェクト: hpfmn/pyacousticmeasure
	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()
コード例 #5
0
ファイル: qtransport.py プロジェクト: dsacre/pyjack
    def refreshUi(self):
	state = jack.get_transport_state()
	frame = jack.get_current_transport_frame()
	rate  = jack.get_sample_rate()
	
	# Jack State
	if (state == 0):
	  self.l_state.setText("Stopped")
	  self.b_play.setChecked(False)
	elif (state == 1):
	  self.l_state.setText("Rolling")
	  self.b_play.setChecked(True)
	elif (state == 3): self.l_state.setText("Starting")
	else: self.l_state.setText("Unknown (%i)" % state)

	# Current Time
	time = frame / rate
	secs = time % 60
	mins = (time / 60) % 60
	hrs  = (time / 3600) % 60
	secH = minH = hrsH = ""
	if secs < 10: secH = "0"
	if mins < 10: minH = "0"
	if hrs  < 10: hrsH = "0"
	self.l_time.setText(hrsH+str(hrs)+":"+minH+str(mins)+":"+secH+str(secs))
	
	# Current Frame
	self.l_frame.setText(str(frame))
コード例 #6
0
ファイル: pyjack.py プロジェクト: spiccinini/stream_grapher
    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
コード例 #7
0
ファイル: inputs.py プロジェクト: shish/mic2midi
        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')
コード例 #8
0
ファイル: mes.py プロジェクト: hpfmn/pyacousticmeasure
	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()
コード例 #9
0
ファイル: blender-jacktrans.py プロジェクト: skisbit/pyjack
def getFrames():
    global ret_blender_curr
    global ret_blender_next
    global ret_jack_current

    currblenframe = Get("curframe")
    currjackframe = jack.get_current_transport_frame()

    rate = jack.get_sample_rate()

    fps = Scene.GetCurrent().getRenderingContext().fps
    fpsBase = Scene.GetCurrent().getRenderingContext().fpsBase
    factor = int(rate / (fps / fpsBase))

    ret_blender_curr = currblenframe * factor
    ret_blender_next = currjackframe / factor
    ret_jack_current = currjackframe
コード例 #10
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)
コード例 #11
0
ファイル: jscope.py プロジェクト: jerasky/plotting-programs
    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)
コード例 #12
0
ファイル: basic.py プロジェクト: leshy/fourier-to-midi
    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
コード例 #13
0
ファイル: player.py プロジェクト: moustaki/echoplay
 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()
コード例 #14
0
ファイル: basic.py プロジェクト: leshy/fourier-to-midi
    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
コード例 #15
0
def print_time():
    print("current time: %f s" %
          (float(jack.get_current_transport_frame()) / jack.get_sample_rate()))
コード例 #16
0
#testing position set/get
from time import sleep
jack.attach("/var/run/jack")
print("getting current time")
print_time()
print("going to frame 0")
jack.transport_locate(0)
sleep(0.2)

print("getting current time")
print_time()

sleep(0.2)
print("going to 6 sec")
jack.transport_locate(jack.get_sample_rate() * 6)
sleep(0.2)

print("getting current time")
print_time()


#testing state set/get
def print_state():
    state = jack.get_transport_state()
    statename = {
        jack.TransportStopped: "stopped",
        jack.TransportRolling: "rolling",
        jack.TransportStarting: "starting"
    }[state]
    print("current state is %i (%s)" % (state, statename))
コード例 #17
0
 def GetSamplingRate(self):
     """
     Returns the sampling rate of the jack server.
     @retval : the sampling rate in floating point format
     """
     return jack.get_sample_rate()
コード例 #18
0
ファイル: transporter.py プロジェクト: dsacre/pyjack
def print_time ():
    time = float(jack.get_current_transport_frame()) / jack.get_sample_rate()
    print "current time: %f s" % time
コード例 #19
0
ファイル: transporter.py プロジェクト: dsacre/pyjack
#testing position set/get
from time import sleep
jack.attach("transporter.py")
print ("getting current time")
print_time()
print ("going to frame 0")
jack.transport_locate(0)
sleep (2)

print ("getting current time")
print_time()

sleep (0.5)
print ("going to 6 sec")
jack.transport_locate(jack.get_sample_rate()*6)
sleep (2)

print ("getting current time")
print_time()

print ("TransportStopped: %i" % jack.TransportStopped)
print ("TransportRolling: %i" % jack.TransportRolling)
print ("TransportStarting: %i" % jack.TransportStarting)
print_state()

print ("playing")
jack.transport_start()
sleep(5)
print ("stopping")
jack.transport_stop()
コード例 #20
0
def print_time ():
    print ("current time: %f s" % (
        float(jack.get_current_transport_frame())/jack.get_sample_rate() 
                    )
          )
コード例 #21
0
ファイル: PlayerThreadSong.py プロジェクト: desfonema/dseq
def get_time():
    return float(jack.get_current_transport_frame()) / jack.get_sample_rate()
コード例 #22
0
def print_time():
    time = float(jack.get_current_transport_frame()) / jack.get_sample_rate()
    print "current time: %f s" % time
コード例 #23
0
ファイル: led-meter.py プロジェクト: mildsunrise/led-meter
    ledtuples = []
    for led in leds:
        led = led.split(":", 1)
        if len(led) >= 2:
            client = clients[int(led.pop(0)) - 1]
        ledtuples.append((client, int(led[0])))

    client = ledp.MultiClient(ledtuples)
    leds = range(len(ledtuples))

    # Setup JACK interface
    jack.attach(arguments["--name"])
    jack.register_port("input",
                       jack.IsInput | jack.IsTerminal | jack.IsPhysical)
    buffer_size = jack.get_buffer_size()
    sample_rate = jack.get_sample_rate()

    def buffer_size_callback():
        raise Exception("buffer size changed and I can't take that")
        exit(2)

    #jack.set_buffer_size_callback(buffer_size_callback) #FIXME
    def sample_rate_callback():
        raise Exception("sample rate changed and I can't take that")
        exit(2)

    #jack.set_sample_rate_callback(sample_rate_callback) #FIXME

    jack_input = np.zeros((1, buffer_size), 'f')
    jack_output = np.zeros((0, buffer_size), 'f')
    output_buffer = range(buffer_size)
コード例 #24
0
ファイル: testtone.py プロジェクト: ispcf/pyjack
#
# 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
    except jack.InputSyncError:
コード例 #25
0
ファイル: colours.py プロジェクト: uniphil/colour-frequencies
    elif hue < 4 / 6.0:
        r, g, b = 0, 1 - scaler, 1
    elif hue < 5 / 6.0:
        r, g, b = scaler, 0, 1
    else:
        r, g, b = 1, 0, 1 - scaler
    return r, g, b


jack.attach("colours")
jack.register_port("in", jack.IsInput)
jack.activate()
jack.connect("system:capture_1", "colours:in")

buff = jack.get_buffer_size()
rate = jack.get_sample_rate()
freqs = np.fft.fftfreq(buff, 1.0 / rate)[: buff / 2]

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))