Example #1
0
    def __init__(self, playbackchannels=1, recordchannels=1):
        """
        @param playbackchannels: the number of channels for playback (can not be changed later)
        @param recordchannels: the number of channels for recording (can not be changed later)
        """
        self.__deleted = True
        # set up jack
        self.__prefix = "SuMPF"
        self.__inputs = []
        self.__outputs = []
        jack.attach(self.__prefix)
        self.__deleted = False
        for i in range(recordchannels):
            portname = "in_" + str(i + 1)
            self.__inputs.append(self.__prefix + ":" + portname)
            jack.register_port(portname, jack.IsInput)
        for i in range(playbackchannels):
            portname = "out_" + str(i + 1)
            self.__outputs.append(self.__prefix + ":" + portname)
            jack.register_port(portname, jack.IsOutput)
        jack.activate()
        # other stuff
        BaseIO.__init__(self, playbackchannels, recordchannels)
#       self.__periods = self.__GetNumberOfPeriods()
        self.__periods = 2
        self.__buffer_size = 0 # This will be set when the interaction with the sound card starts
Example #2
0
def index():

    ports = None
    try:
        ports = jack.get_ports()
    except (jack.NotConnectedError, jack.Error):
        try:
            jack.detach('studio-webapp')
            jack.attach('studio-webapp')
            ports = jack.get_ports()
        except (jack.NotConnectedError, jack.Error):
            return render_template('jack_device_error.html')

    inports = []
    outports = []
    connects = {}

    for port in ports:
        if (jack.get_port_flags(port) & jack.IsInput) > 0:
            inports.append(port)
            connects[port] = jack.get_connections(port)
        if (jack.get_port_flags(port) & jack.IsOutput) > 0:
            outports.append(port)
    try:
        otg_systemd_status = subprocess.check_output(['sudo',
                                                      'systemctl',
                                                      'is-active',
                                                      'studio-gaudio_in'])
    except subprocess.CalledProcessError, e:
        otg_systemd_status = 'failed'
Example #3
0
def arranca_resampler(card, rate, mode):
    """ mode puede ser: zita-a2j, zita-j2a, alsa_in, alsa_out
    """
    resamplerIsRunning = False
    if "zita" in mode:
        # este es el verdadero arranque de zita:
        resamplerIsRunning = zitaJack(card, rate, mode,
                                      log=False)  #  ver la funcion zitaJack
    elif "alsa" in mode:
        resamplerIsRunning = alsaInOut(card, rate, mode)

    if resamplerIsRunning:
        # esperamos a que los puertos zita aparezcan en jack
        jack.attach('tmp')
        intentos = 8
        encontrado = False
        while intentos:
            for port in jack.get_ports():
                if bareCard(card) in port:
                    encontrado = True
            if encontrado:
                print "(soundcards) Se ha reiniciado " + mode + " " + card + " " + rate
                break
            intentos -= 1
            print "(soundcards) Esperando a " + mode + "." * (8 - intentos + 1)
            sleep(.25)
        if not intentos:
            print "(soundcards) (!) No está disponible el puerto " + bareCard(
                card) + " en jack"
        jack.detach()
    else:
        print "(soundcards) <!> No se ha podido reiniciar " + mode + " en " + card + " " + rate
Example #4
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
Example #5
0
def unroute(source, destination):
    try:
        jack.disconnect(source, destination)
    except jack.NotConnectedError:
        jack.attach("studio-webapp")
        jack.disconnect(source, destination)

    return ''
Example #6
0
def unroute(source, destination):
    try:
        jack.disconnect(source, destination)
    except jack.NotConnectedError:
        jack.attach("studio-webapp")
        jack.disconnect(source, destination)

    return ''
Example #7
0
 def connect(self):
     try :
         jack.attach("sooperlooper")
         jack.activate()
         jack.connect("sooperlooper:common_out_1", "alsa_pcm:playback_1")
         jack.connect("sooperlooper:common_out_2", "alsa_pcm:playback_2")
     except :
         print("Run jack and sooperlooper")
         sys.exit(1) 
Example #8
0
 def run(self):
     self.ALSA()
     self.GST()
     jack.attach(self.exe.handler.server.name)
     jack.activate()
     self.Jack()
     self.Play()
     self.cleanup()
     return self.statuses
Example #9
0
 def track_playback_started(self, tl_track):
     print "Attaching to jack."
     jack.attach("default")
     print "Attached."
     print "Jack ports: %s", jack.get_ports()
     
     print "Track playback started. Time for some JACK magic."
     
     # Connect the specified JACK ports together.
     jack.connect("mopidy:out_jackaudiosink0_1","python:in_openob_tx_test-link_1")
     jack.connect("mopidy:out_jackaudiosink0_2","python:in_openob_tx_test-link_2")
Example #10
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')
Example #11
0
def load_jt(options):
    """ arranca jacktrip y lo primero que hacemos es deshacer la conexión 
        automática que jacktrip hace a los puertos system de jack (!)
        Las opciones pueden ser:
        -c remoteHost (modo cliente)
        -s            (modo servidor)
    """
    # muteamos la tarjeta de sonido
    sc.alsa_mute_system_card("on")
    # arranca jacktrip
    Popen("killall jacktrip", shell=True)
    sleep(.5)
    Popen("jacktrip -z -q 8 -r 2 " + options + " >/dev/null 2>&1", shell=True)
    # esperamos a jacktrip:
    intentos = 20  # * 0.25 = 5 segundos
    while intentos:
        try:
            if "JackTrip" in check_output("jack_lsp", shell=True):
                print "(jacktrip.py) Ha arrancado Jacktrip."
                break
        except:
            pass
        intentos -= 1
        sleep(.25)
    if not intentos:
        print "(jacktrip.py) Error arrancando Jacktrip"
        sys_exit(-1)

    # (!) lo primero deshacemos la conexión automática a system
    jack.attach("tmp")
    jack.disconnect("JackTrip:receive_1", "system:playback_1")
    jack.disconnect("JackTrip:receive_2", "system:playback_2")
    try:
        jack.disconnect("system:capture_1", "JackTrip:send_1")
        jack.disconnect("system:capture_2", "JackTrip:send_2")
    except:
        # es posible que sea un FIRtro pequeño sin system:capture
        pass
    jack.detach()

    # modo client
    if "-c" in options:
        # La conexión a FIRtro se gestiona cambiando la input en FIRtro.
        pass

    # modo server
    if "-s" in options:
        connect_source2jacktrip()

    sc.alsa_mute_system_card("off")
Example #12
0
def change_input(input_name, in_ports, out_ports, resampled="no"):

    # 'in_ports':   Lista [L,R] de los puertos capture de jack de la fuente elegida
    # 'out_ports':  Lista de los puertos de la variable 'firtro_ports' que se resuelve
    #               en server_process en función de si se usa Brutefir/Ecasound

    # FIRtro2: evaluamos si la entrada requiere resampling por estar en una tarjeta adicional
    if resampled <> "no":
        sc.external_card_resync(in_ports, resampled)

    # CONMUTADOR, como el original de FIRtro1.
    try:
        jack.attach("tmp")

        # Desconectamos todo lo que hubiera en la entrada de FIRtro (y en los posibles monitores):
        desconecta_fuentes_de(out_ports)

        # Posibles PAUSAS opcionales en los PLAYERS INTEGRADOS (ahorro de %CPU):
        players.manage_pauses(input_name)

        # Y ahora conectamos la entrada deseada a FIRtro y a los monitores:
        for i in range(len(in_ports)):
            # Entradas a FIRtro
            try:
                jack_connect(in_ports[i], out_ports[i])
            except:
                logging.exception("error conectando " + in_ports[i] + " <> " +
                                  out_ports[i])

            # Los monitores opcionales:
            try:
                if ext_monitor_ports:
                    jack_connect(in_ports[i], ext_monitor_ports[i])
                    jack_connect(in_ports[i], int_monitor_ports[i])
            except:
                logging.exception("error en conexion de monitores")

        jack.detach()

    except:

        # Si hay alguna excepción devolvemos boolean False
        logging.exception("error en cuerpo ppal")
        jack.detach()
        print "(server_input) Problemas (ver ~/tmp/server_input.log)"
        return False

    # Y si todo ha ido bien, devolvemos el boolean True
    return True
Example #13
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)
Example #14
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)
Example #15
0
    def open(self):
        self.client = jack.attach('PythonClient')
        myname = jack.get_client_name()

        jack.register_port("in_1", jack.IsInput)
        jack.register_port("in_2", jack.IsInput)
        jack.register_port("out", jack.IsOutput)
        self.client.activate()

        print "Jack ports (before):", jack.get_ports()
        jack.connect("system:capture_1", myname+":in_1")
Example #16
0
def main():

    try:
        # Nos conectamos al servidor jack bajo el nombre "pecador"
        jack.attach("pecador")
    except:
        print "algo va mal no puedorrr conectar a jack"
        sys.exit()

    # Lanzamos ebumeter. Ebumeter no admite argumentos, 
    # requiere conectar sus puertos en jack a posteriori.
    dummy = Popen(["killall", "ebumeter"], stdout=None, stderr=None)
    time.sleep(.5)
    dummy = Popen(["ebumeter"], stdout=None, stderr=None)
    time.sleep(.5)
    
    # Conectamos a Ebumeter los mismos puertos que están conectados a Brutefir:
    conect2ebumeter(BrutefirPorts())

    # Nos desconectamos de Jack
    jack.detach()
Example #17
0
def index():
    try:
        ports = jack.get_ports()
    except jack.NotConnectedError:
        jack.attach('studio-webapp')
        ports = jack.get_ports()

    inports = []
    outports = []
    connects = {}

    for port in ports:
        if (jack.get_port_flags(port) & jack.IsInput) > 0:
            inports.append(port)
            connects[port] = jack.get_connections(port)
        if (jack.get_port_flags(port) & jack.IsOutput) > 0:
            outports.append(port)
    try:
        otg_systemd_status = subprocess.check_output(
            ['sudo', 'systemctl', 'is-active', 'studio-gaudio_in'])
    except subprocess.CalledProcessError, e:
        otg_systemd_status = 'failed'
Example #18
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
Example #19
0
def jackConexiones(nombrePuerto="", direccion="*"):
    """ direccion: > | < | *
        Devuelve una lista de tripletas:
        (puerto, conexion, puerto)
    """
    ports = []
    jack.attach("tmp")
    for puerto in [x for x in jack.get_ports() if nombrePuerto in x]:
        conexiones = jack.get_connections(puerto)
        for conexion in conexiones:
            flags = jack.get_port_flags(conexion)
            # Returns an integer which is the bitwise-or of all flags for a given port.
            # haciendo pruebas veamos algunos flags de puertos:
            # puertos escribibles (playback): 1 21     impares, ultimo bit a 1
            # puertos leibles     (capture) : 2 18 22  pares,   ultimo bit a 0
            if flags % 2:
                direc = ">"
            else:
                direc = "<"
            if direc == direccion or direccion == "*":
                ports.append((puerto, " --" + direc + "-- ", conexion))
    jack.detach()
    return ports
Example #20
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()
Example #21
0
def conecta_tarjeta(vias):

    jack.attach("tmp")

    # Disponemos de la funcion brutefir.outputsMap que contiene
    # el mapeo de vias tal como esta definido en brutefir_config, por ejemplo:
    #   system:playback_3/hi_L
    #   system:playback_4/hi_R
    #   system:playback_7/lo_L
    #   system:playback_8/lo_R
    #   system:playback_5/sw1
    #   system:playback_6/sw2

    to_disconnect=[]
    to_connect = []

    # Ahora debemos evaluar si es una salida a activar:
    for bfOutMap in brutefir.outputsMap:
        conectar = False
        jackDest, bfOut = bfOutMap.split('/')
        jackOrig        = "brutefir:" + bfOut

        for via in vias:
            if via.lower() in bfOut.lower():
                conectar = True

        if conectar:
            to_connect.append( (jackOrig, jackDest) )
        else:
            to_disconnect.append( (jackOrig, jackDest) )

    for pair in to_disconnect:
        jack.disconnect(pair[0], pair[1])
    for pair in to_connect:
        jack.connect(pair[0], pair[1])

    jack.detach()
Example #22
0
def connect_source2jacktrip():
    jack.attach("tmp")
    # Desconectamos lo que hubiera en JackTrip
    c1_ports = jack.get_connections("JackTrip:send_1")
    c2_ports = jack.get_connections("JackTrip:send_2")
    for p1 in c1_ports:
        jack.disconnect(p1, "JackTrip:send_1")
    for p2 in c2_ports:
        jack.disconnect(p2, "JackTrip:send_2")
    try:
        # conectamos las fuente del FIRtro a jacktrip
        s1_ports = jack.get_connections(firtro_ports[0])
        s2_ports = jack.get_connections(firtro_ports[1])
        for s1 in s1_ports:
            jack.connect(s1, "JackTrip:send_1")
        for s2 in s2_ports:
            jack.connect(s2, "JackTrip:send_2")
    except:
        # el motivo del fallo es que los puertos de JackTrip no están activos:
        # "Cannot connect ports owned by inactive clients: "JackTrip" is not active"
        # porque no ha sincronizado todavía con un cliente.
        print "(jacktrip.py) (i) para conectar puertos se necesita que estén"
        print "                  activos (con una conexion cliente jacktrip en red)"
    jack.detach()
Example #23
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
Example #24
0
import time
import jack
import soundfile
import arduino
import telephone
import numpy
import conversation
import socket


import gobject
gobject.threads_init()

print "Connecting to jackd"
jack.attach("pleasehold")
# All sound works via jackd -- so if you want multiple sound cards, then glue them together with ALSA

from tempfile import TemporaryFile
outfile = TemporaryFile()


conversations = list()
telephones = list()
barqueue = list()

phonemap = ['44','41','50','58','56','54','51','9','57','43','40','53','52','55','59']

if not "rose" in open("/etc/hostname").read():
	channels = 15
	
Example #25
0
 def attach(self):
     jack.attach(self.name)
Example #26
0
def init(ini, device, alsaClients, _tempo, _measureLength, debugLevel):
    '''Initiate all variables an devices/classes.'''
    global seq, mon, buttons, tracks, tempo, measureLength
    tempo = _tempo
    measureLength = _measureLength

    # init logging
    numeric_level = getattr(logging, debugLevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
    logging.basicConfig(level=numeric_level,
                        format='[%(levelname)s] %(asctime)s - %(message)s')

    # initiate MIDI sequencer
    seq = midi.sequencer.SequencerWrite(alsa_sequencer_name='moseq',
                                        alsa_port_name='moseq in',
                                        alsa_queue_name='moseq queue')
    hardware = midi.sequencer.SequencerHardware()
    for iclient in alsaClients:
        # split string at ':'
        tmp = iclient.split(':')
        if len(tmp) <= 1:
            port = '0'
        else:
            port = tmp[1]
        client = tmp[0]

        try:
            # try to parse integers
            port = int(port)
            try:
                client = int(client)
            except ValueError:
                # fallback: handle named client name
                client = hardware.get_client(client).client
        except ValueError:
            # fallback: handle named client and port
            client, port = hardware.get_client_and_port(client, port)
        seq.subscribe_port(client, port)
    seq.start_sequencer()

    # init monome
    mon = monome.Monome(device)
    mon.led_all(0)
    buttons = [[0 for x in range(mon.columns)] for y in range(mon.rows)]

    # init connection to jack
    jack.attach('moseq')

    # read in config file and init tracks
    parser = ConfigParser.SafeConfigParser()
    parser.read(ini)
    regSection = re.compile(r'track(?P<track>[0-9]+)')
    for isec in parser.sections():
        m = regSection.match(isec)
        if not m:
            # no track configuration section... ignore
            continue

        try:
            # get track number
            i = int(m.group('track'))

            # init a new Track
            vals = dict(parser.items(isec))
            tracks[i] = Track(mon.columns,
                              startEvent=vals.get('start'),
                              stopEvent=vals.get('stop'),
                              channel=int(vals.get('channel', -1)),
                              tickOffset=vals.get('tickOffset', 0))
        except ValueError:
            continue

    # start main loop
    print 'Starting main loop...'
    loop()
Example #27
0
#!/usr/bin/python
import jack
import time
name="default"
time.sleep(1)
jack.attach(name)
bs=jack.get_buffer_size()
print("'%s'.buffer_size = %d" % (name, bs));
Example #28
0
        # self.update_time += 20
        # print("setting update time to %d" %(self.update_time))
        pass
    except jack.OutputSyncError:
        print "Output Sync Error"
        pass


def reset_view():
    [p.setYRange(-1, 1) for p in plots]
    [p.enableAutoRange(axis=pg.ViewBox.XAxis, enable=True)]


# initialize jack connections
nscopes = 1
jack.attach("jscope")
for i in range(nscopes):
    jack.register_port("in_%d" % (i), jack.IsInput)
jack.activate()
N = jack.get_buffer_size()
Sr = float(jack.get_sample_rate())
print (Sr)
plotlength = 0.3
abscissa = np.flipud(-np.arange(Sr * plotlength) / Sr)
print (len(abscissa))
resample_factor = int(abscissa.size / 1000)

rings = [RingBuffer(len(abscissa)) for i in range(nscopes)]

input_slice = np.zeros((nscopes, N), dtype="f")
output_slice = input_slice.copy()
Example #29
0
#!/usr/bin/python
# Capture 3 seconds of stereo audio from alsa_pcm:capture_1/2; then play it back.
#
# 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 Numeric
import jack
import time
from numpy.fft import rfft
from pylab import *
from numpy import *
import math

jack.attach("fftknn")

print jack.get_ports()

jack.register_port("in_1", jack.IsInput)
jack.register_port("out_1", jack.IsOutput)

jack.activate()

# jack.connect("alsa_pcm:capture_1", "fftknn:in_1")
# jack.connect("Hydrogen-1:out_L", "fftknn:in_1")
# jack.connect("pure_data_0:output0", "fftknn:in_1")
# jack.connect("sooperlooper:common_out_1", "fftknn:in_1")

print jack.get_connections("fftknn:in_1")
Example #30
0
    # Parse LED specification, create multiclient
    leds = arguments["<leds>"].split(",")
    client = clients[0]
    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
Example #31
0
 def attach_to_jack(self):
     jack.attach("mainserver")
Example #32
0
    # Parse LED specification, create multiclient
    leds = arguments["<leds>"].split(",")
    client = clients[0]
    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')
Example #33
0
#!/usr/bin/python
# Capture 3 seconds of stereo audio from alsa_pcm:capture_1/2; then play it back.
#
# 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 Numeric
import jack
import time
from numpy.fft import rfft
from pylab import *
from numpy import *
import math

jack.attach("fftknn")

print jack.get_ports()

jack.register_port("in_1", jack.IsInput)
jack.register_port("out_1", jack.IsOutput)

jack.activate()

# jack.connect("alsa_pcm:capture_1", "fftknn:in_1")
# jack.connect("Hydrogen-1:out_L", "fftknn:in_1")
# jack.connect("pure_data_0:output0", "fftknn:in_1")
# jack.connect("sooperlooper:common_out_1", "fftknn:in_1")

print jack.get_connections("fftknn:in_1")
Example #34
0
 def attach(self):
     jack.attach(self.name)
Example #35
0
from Blender import *

play_button = Draw.Create(False)
BEV_PLAY = 1
BEV_EXIT = 2
BEV_PREV = 3
BEV_NEXT = 4
BEV_START = 5
ret_blender_curr = 0
ret_blender_next = 0
ret_jack_current = 0
prev_blen = 0
prev_jack = 0

try:
    jack.attach("/var/run/jack-blender")
except jack.UsageError:
    pass  # continue using exist jack if script crashed but jack still online


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
Example #36
0
        curve = visual.curve(color=visual.color.white, display=self.g, radius=0)

        for point in zip(range(len(data)),data):
            r = g = b = 1
            curve.append(pos=(point[0],point[1] * 10,0), color=(r,g,b))
        self.curves.insert(0,curve)

#out = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK)
#out.setchannels(1)
#out.setrate(rate)
#out.setformat(alsaaudio.PCM_FORMAT_S16_LE)
#out.setperiodsize(slen)
#inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

jack.attach("captest")
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()

jack.connect("system:capture_1", "captest:in_1")
jack.connect("system:capture_2", "captest:in_1")
jack.connect("captest:out_1", "system:playback_1")
jack.connect("captest:out_1", "system:playback_2")

buffer_size = jack.get_buffer_size()
sample_rate = float(jack.get_sample_rate())
Example #37
0
        elif opc.startswith("sink="):
            sink = str(opc.split("=")[-1])

        elif opc.startswith("name="):
            ownname = str(opc.split("=")[-1])

        elif opc == "-d":
            disconnect = True

        elif "-h" in opc:
            print __doc__
            sys.exit()

    # Nos atachamos a jackd
    jack.attach(ownname)

    # Creamos los puertos de esta instancia
    for i in range(1, 1 + nchannels):
        jack.register_port('out_' + str(i), jack.IsOutput)
        jack.register_port("in_"  + str(i), jack.IsInput)

    # Activamos los puertos
    jack.activate()

    # Conectamos los puertos de captura y playback deseados:
    if source:
        if disconnect:
            conecta(source, sink, mode='disconnect')
        conecta(source, ownname, mode='connect')
    if sink:
Example #38
0
 def __init__(self, manager, **kwargs):
     super(Speaker, self).__init__(**kwargs)
     self._manager = manager
     jack.attach("sooperlooper")
     jack.activate()
Example #39
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import jack, os, sys
from PyQt4.QtGui import QApplication, QDialog
from PyQt4.QtCore import QTimer, SIGNAL, SLOT
from PyQt4.uic import loadUi

jack.attach("qtransport")


class MainW(QDialog):
    def __init__(self, *args):
        QDialog.__init__(self, *args)
        loadUi(sys.path[0] + "/qtransport_gui.ui", self)

        self.timer = QTimer()
        self.timer.start(100)

        self.connect(self.b_back, SIGNAL("clicked()"), self.goBack)
        self.connect(self.b_play, SIGNAL("clicked()"), self.play)
        self.connect(self.b_stop, SIGNAL("clicked()"), self.stop)
        self.connect(self.b_forward, SIGNAL("clicked()"), self.goForward)
        self.connect(self.timer, SIGNAL("timeout()"), self.refreshUi)

    def goBack(self):
        pos = int(jack.get_current_transport_frame()) - 100000
        if pos < 0:
            jack.transport_locate(0)
        else:
            jack.transport_locate(pos)
Example #40
0
import jack

def print_time ():
    print ("current time: %f s" % (
        float(jack.get_current_transport_frame())/jack.get_sample_rate() 
                    )
          )

#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()
Example #41
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import jack, os, sys
from PyQt4.QtGui import QApplication, QDialog
from PyQt4.QtCore import QTimer, SIGNAL, SLOT
from PyQt4.uic import loadUi

jack.attach("qtransport")

class MainW(QDialog):
    def __init__(self, *args):
        QDialog.__init__(self, *args)
        loadUi(sys.path[0]+"/qtransport_gui.ui", self)
        
        self.timer = QTimer()
        self.timer.start(100)
        
        self.connect(self.b_back, SIGNAL("clicked()"), self.goBack)
        self.connect(self.b_play, SIGNAL("clicked()"), self.play)
        self.connect(self.b_stop, SIGNAL("clicked()"), self.stop)
        self.connect(self.b_forward, SIGNAL("clicked()"), self.goForward)
        self.connect(self.timer, SIGNAL("timeout()"), self.refreshUi)
        
    def goBack(self):
	pos = int(jack.get_current_transport_frame()) - 100000
	if pos < 0:
	  jack.transport_locate(0)
	else:
	  jack.transport_locate(pos)
Example #42
0
    time = float(jack.get_current_transport_frame()) / jack.get_sample_rate()
    print "current time: %f s" % 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))

#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")
Example #43
0

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


#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")
Example #44
0
    output_n = 2
    print 'Minimum output port number is 2'
elif args.outports > 10:
    if channels == 2:
        output_n = 10
        print 'Sorry, 20 outputs is the maximum output port number'
    elif args.outports > 20:
        output_n = 20
        print 'Sorry, 20 outputs is the maximum output port number'
else:
    output_n = args.outports

output_ports = [True] + [False]*(output_n-1) if output_n>0 else []
active = 0

jack.attach(client_name)
buf_size = jack.get_buffer_size()
#sam_size = float(jack.get_sample_rate())
#capture = numpy.zeros((2,int(sam_size)), 'f')

input_stream = numpy.zeros((channels, buf_size), 'f')
empty_stream = numpy.zeros((channels, buf_size), 'f')
#output_stream = numpy.zeros((4, buf_size), 'f')
#input_buffer = numpy.zeros((2, buf_size), 'f')

input_ports = []
if channels == 2:
    jack.register_port('input L', jack.IsInput)
    input_ports.append(client_name + ':' + 'input L')
    jack.register_port('input R', jack.IsInput)
    input_ports.append(client_name + ':' + 'input R')
Example #45
0
import jack


def print_time():
    print("current time: %f s" %
          (float(jack.get_current_transport_frame()) / jack.get_sample_rate()))


#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():
Example #46
0
#!/usr/bin/python
import jack
import time
name = "default"
time.sleep(1)
jack.attach(name)
bs = jack.get_buffer_size()
print("'%s'.buffer_size = %d" % (name, bs))
Example #47
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 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
import pysoundfile
import time

jack.attach("pymetro")
jack.register_port("out_1", jack.IsOutput)
jack.register_port("in_1", jack.IsInput)
jack.activate()
#print(jack.get_ports())
jack.connect("pymetro:out_1", "system:playback_1")
jack.connect("pymetro:out_1", "system:playback_2")

N = jack.get_buffer_size()
Sr = float(jack.get_sample_rate())

output_file = pysoundfile.SoundFile('MetronomeUp.wav')
output = output_file.read()
output = 0.225*output/numpy.max(output)

print(output.shape)
input = numpy.zeros((1,N), 'f')
print(N)
Example #48
0
                             radius=0)

        for point in zip(range(len(data)), data):
            r = g = b = 1
            curve.append(pos=(point[0], point[1] * 10, 0), color=(r, g, b))
        self.curves.insert(0, curve)


#out = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK)
#out.setchannels(1)
#out.setrate(rate)
#out.setformat(alsaaudio.PCM_FORMAT_S16_LE)
#out.setperiodsize(slen)
#inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

jack.attach("captest")
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()

jack.connect("system:capture_1", "captest:in_1")
jack.connect("system:capture_2", "captest:in_1")
jack.connect("captest:out_1", "system:playback_1")
jack.connect("captest:out_1", "system:playback_2")

buffer_size = jack.get_buffer_size()
sample_rate = float(jack.get_sample_rate())
Example #49
0
            out_buffer[0,i]=self.sample[int(self.playpos)]
            self.playpos+=self.playstep
        return out_buffer
    def setNote(self, note):
        print("got note ", note)
        semitones=note-self.keynote
        self.note=note
        self.playstep=2**(semitones/12.0)
        self.playpos=0
    def stopNote(self,note):
        if note==self.note:
            self.note=0
            self.playpos=0
            self.playstep=0

jack.attach("pysampl")
jack.register_port("out_1", jack.IsOutput)
jack.register_port("in_1", jack.IsInput)
jack.activate()
jack.connect("pysampl:out_1", "system:playback_1")
jack.connect("pysampl:out_1", "system:playback_2")

N = jack.get_buffer_size()
Sr = float(jack.get_sample_rate())
input_buf = numpy.zeros((1,N), 'f')

output, samplerate = soundfile.read('Sample.wav')
output = 0.225*output/numpy.max(output)

mysampl = sampler(output, 60)
Example #50
0
import threading
import time
import Queue
import jack
from util import nanosleep
from models import Sequence

jack.attach("dseq")

def get_time():
    return float(jack.get_current_transport_frame()) / jack.get_sample_rate()

#testing state set/get
def get_state():
    return jack.get_transport_state()

time.sleep = nanosleep.nanosleep
TICKS_PER_BEAT = 24

class PlayerThreadSong(threading.Thread):
    def __init__(self, conn):  
        threading.Thread.__init__(self)
        #Position means pattern if playing a channel, or cursor pos if playing pattern 
        self.__pos = 0
        self.__conn = conn
        self.__quit = False
        self.__playing = False
        self.__repeat = False
        
    def play(self, data, bpm, repeat = False):
            
Example #51
0
    if hue < 1 / 6.0:
        r, g, b = 1, scaler, 0
    elif hue < 2 / 6.0:
        r, g, b = 1 - scaler, 1, 0
    elif hue < 3 / 6.0:
        r, g, b = 0, 1, scaler
    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")
Example #52
0
scale_windowsize = int(300 / UPDATE_INTERVAL)
vu_value = TARGET_CHANNELS * [0]
random_gain = TARGET_CHANNELS * [1.0]

net = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
net.connect((CCC_HOST, CCC_PORT))
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)
Example #53
0
            info.append("(i) conectando "+ o + " " + d)
            jack.connect(o,d)

    # Conectamos los pares:
    for o in source_ports[1::2]:
        for d in getDisplaysPorts()[1::2]:
            info.append("(i) conectando "+ o + " " + d)
            jack.connect(o,d)

    if info:
        for cosa in info:
            print cosa
    else:
        print "(?) nada que conectar"
        
if __name__ == "__main__":

    try:
        # Nos conectamos al servidor jack bajo el nombre "tmp" por poner algo
        jack.attach("tmp")
        conectaDISPLAYS()
        jack.detach()
    except:
        print "problemas de conexion python a JACK, que lo sepas"






Example #54
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 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:
Example #55
0
def init(ini, device, alsaClients, _tempo, _measureLength, debugLevel):
    """Initiate all variables an devices/classes."""
    global seq, mon, buttons, tracks, tempo, measureLength
    tempo = _tempo
    measureLength = _measureLength

    # init logging
    numeric_level = getattr(logging, debugLevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError("Invalid log level: %s" % loglevel)
    logging.basicConfig(level=numeric_level, format="[%(levelname)s] %(asctime)s - %(message)s")

    # initiate MIDI sequencer
    seq = midi.sequencer.SequencerWrite(
        alsa_sequencer_name="moseq", alsa_port_name="moseq in", alsa_queue_name="moseq queue"
    )
    hardware = midi.sequencer.SequencerHardware()
    for iclient in alsaClients:
        # split string at ':'
        tmp = iclient.split(":")
        if len(tmp) <= 1:
            port = "0"
        else:
            port = tmp[1]
        client = tmp[0]

        try:
            # try to parse integers
            port = int(port)
            try:
                client = int(client)
            except ValueError:
                # fallback: handle named client name
                client = hardware.get_client(client).client
        except ValueError:
            # fallback: handle named client and port
            client, port = hardware.get_client_and_port(client, port)
        seq.subscribe_port(client, port)
    seq.start_sequencer()

    # init monome
    mon = monome.Monome(device)
    mon.led_all(0)
    buttons = [[0 for x in range(mon.columns)] for y in range(mon.rows)]

    # init connection to jack
    jack.attach("moseq")

    # read in config file and init tracks
    parser = ConfigParser.SafeConfigParser()
    parser.read(ini)
    regSection = re.compile(r"track(?P<track>[0-9]+)")
    for isec in parser.sections():
        m = regSection.match(isec)
        if not m:
            # no track configuration section... ignore
            continue

        try:
            # get track number
            i = int(m.group("track"))

            # init a new Track
            vals = dict(parser.items(isec))
            tracks[i] = Track(
                mon.columns,
                startEvent=vals.get("start"),
                stopEvent=vals.get("stop"),
                channel=int(vals.get("channel", -1)),
                tickOffset=vals.get("tickOffset", 0),
            )
        except ValueError:
            continue

            # start main loop
    print "Starting main loop..."
    loop()