Exemplo n.º 1
0
 def __new__(cls, port_name=None):
     """Open a named port."""
     if MidiPort.__instance is None:
         if port_name is not None:
             MidiPort.__instance = mido.open_output(port_name)
         else:
             MidiPort.__instance = mido.open_output()
     return MidiPort.__instance
Exemplo n.º 2
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input('Launchpad S', callback=True)
            except IOError:
                input = mido.open_input('Launchpad S MIDI 1', callback=True)
        if output is None:
            try:
                output = mido.open_output('Launchpad S')
            except IOError:
                output = mido.open_output('Launchpad S MIDI 1')

        super(LaunchpadS, self).__init__(input, output)
Exemplo n.º 3
0
    def __init__(self, target=MIDIOUT_DEFAULT):
        self.midi = None
        self.debug = False
        ports = mido.get_output_names()
        if len(ports) == 0:
            raise Exception("No MIDI output ports found")

        for name in ports:
            if name == target:
                isobar.log("Found MIDI output (%s)" % name)
                self.midi = mido.open_output(name)

        if self.midi is None:
            print "Could not find MIDI target %s, using default" % target
            self.midi = mido.open_output()
Exemplo n.º 4
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input('Launchpad Mini', callback=True)
            except IOError:
                input = mido.open_input('Launchpad Mini MIDI 1', callback=True)
        if output is None:
            try:
                output = mido.open_output('Launchpad Mini')
            except IOError:
                output = mido.open_output('Launchpad Mini MIDI 1')

        self.lights = lights((8, 8))
        self.buttons = buttons((8, 8))

        super(Launchpad, self).__init__(input, output)
Exemplo n.º 5
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input('Launchpad Pro Standalone Port', callback=True)
            except IOError:
                input = mido.open_input('Launchpad Pro MIDI 2', callback=True)
        if output is None:
            try:
                output = mido.open_output('Launchpad Pro Standalone Port')
            except IOError:
                output = mido.open_output('Launchpad Pro MIDI 2')

        self.lights = lights((8, 8))
        self.buttons = buttons((8, 8))

        super(LaunchpadPro, self).__init__(input, output)
Exemplo n.º 6
0
    def __init__(self, _save_path, songfile, _plyr_ctrls):
        super(PlayerThread, self).__init__()
        self.name = 'Player'
        self.stoprequest = threading.Event()
        self.plyr_ctrls = _plyr_ctrls
        self.chan_roles = [0 for i in range(10)]
        self.plyr_ctrls['songfile'] = songfile
        self.midifile = MidiFile(_save_path + songfile)
        # 0 - drum fill
        self.counter = [0 for i in range(4)]
        self.wt = WolfTonesSong()
        self.save_path = _save_path
        self.load_song(songfile)
        self.alt_meas = []

        #get the portname (system specific)
        env = socket.gethostname()
        if(env == 'record_synth'):
            names = str(mido.get_output_names())
            ports = names.split(',')
            sobj = re.search(r'Synth input port \(\d*:0\)', ports[0], flags=0)
            portname = sobj.group()
        if(env == 'colinsullivan.me'):
            #dummy port for testing on a headless server with no audio
            portname = 'Midi Through:Midi Through Port-0 14:0'
        self.outport = mido.open_output(portname, autoreset=True)
Exemplo n.º 7
0
  def __init__(self, input_midi_port, output_midi_port, texture_type,
               passthrough=True):
    self._texture_type = texture_type
    self._passthrough = passthrough
    # When `passthrough` is True, this is the set of open MIDI note pitches.
    self._open_notes = set()
    # This lock is used by the serialized decorator.
    self._lock = threading.RLock()
    # A dictionary mapping a string-formatted mido.Messages to a condition
    # variable that will be notified when a matching messsage is received,
    # ignoring the time field.
    self._signals = {}
    # A dictionary mapping integer control numbers to most recently-received
    # integer value.
    self._control_values = {}
    # Threads actively being used to capture incoming messages.
    self._captors = []
    # Potentially active player threads.
    self._players = []
    self._metronome = None

    # Open MIDI ports.
    self._inport = (
        input_midi_port if isinstance(input_midi_port, mido.ports.BaseInput)
        else mido.open_input(
            input_midi_port,
            virtual=input_midi_port not in get_available_input_ports()))
    self._outport = (
        output_midi_port if isinstance(output_midi_port, mido.ports.BaseOutput)
        else mido.open_output(
            output_midi_port,
            virtual=output_midi_port not in get_available_output_ports()))

    # Start processing incoming messages.
    self._inport.callback = self._timestamp_and_handle_message
Exemplo n.º 8
0
    def open_output(self):
        if self.backend == 'mido':
            if self.debug>0:
                print('------ OUTPUT ------')
                for port in mido.get_output_names():
                  print(port)
                print('-------------------------')
            try:
                self.outputport  = mido.open_output(self.config.get('midi', 'device'))
                print "Connected to MIDI output"
            except:
                print "Error: cannot connect to MIDI output"
                raise RuntimeError("Error: cannot connect to MIDI output")

        elif self.backend == 'midiosc':
            try:
                self.outputport = OSC.OSCClient()
                self.outputport.connect((self.config.get('midi','hostname'), self.config.getint('midi','port')))
                print "Connected to OSC server"
            except:
                print "Error: cannot connect to OSC server"
                raise RuntimeErrror("cannot connect to OSC server")

        else:
            print 'Error: unsupported backend: ' + self.backend
            raise RuntimeError('unsupported backend: ' + self.backend)
Exemplo n.º 9
0
def main():
    output_name = ''
    input_name = ''
    device_names = mido.get_input_names()
    for device_name in device_names:
        # FIXME: Heuristic to get our USB stick device
        if '-' in device_name and 'Through' not in device_name:
            output_name = device_name
            break
    else:
        print "No appropriate MIDI device. MIDI device names: ", device_names
        return

    print "Connected devices: ", device_names
    print "Opening device: ", output_name

    # or, with mido.open_ioport(output_name) as iop:
    with mido.open_output(output_name) as output:
        with mido.open_input(output_name, callback=print_message) as inp:
            #msg = mido.Message('sysex', data=[10]) Set type to digital output
            #msg = mido.Message('sysex', data=[101]) # send watchdog timer reset
            #msg = mido.Message('sysex', data=[99]) # Request device type
            msg = mido.Message('sysex', data=[77]) # Request device name
            #msg = mido.Message('sysex', data=[54,1,2,3,4]) # Set device name to '0x010203'
            #msg = mido.Message('note_on')
            print "sending msg: ", msg
            output.send(msg);
            print "waiting for response message"
            time.sleep(1) # Pause while we get MIDO callback print-outs
    print "script done"
Exemplo n.º 10
0
def Run(fi, minnote=21, maxnote=108, forcelowest=False, minvelocity=64, maxvelocity=115, timingdivisor=127, shortestnoteon=0.00390625, step=3, mono=True, microgranny=True, sendCC=True, sendsamplechange=True, loop=False):

    if minnote < 0:
        print("Negative minimum note")
        minnote = 0
        
    if maxnote >127:
        print("Maximum note too high")
        maxnote = 127

    if maxnote < minnote or minnote > maxnote:
        print("Maxnote and minnote swapped")
        hold = maxnote
        maxnote = minnote
        minnote = hold

    ##open file as a byte array
    with open(fi, "rb") as inFile:
        f = inFile.read()
        b = bytearray(f)

    ##send midi
    with mido.open_output() as o:
        if(loop):
            while True:
                print("looping")
                Play(o, b,minnote,maxnote, forcelowest, minvelocity, maxvelocity, timingdivisor,shortestnoteon,step,mono,microgranny,sendCC,sendsamplechange)
                
        else:
            Play(o, b,minnote,maxnote,forcelowest, minvelocity, maxvelocity,timingdivisor,shortestnoteon,step,mono,microgranny,sendCC,sendsamplechange)
Exemplo n.º 11
0
def Run():
    global mt
    global nvalue
    global pnvalue
    
    with mido.open_output(autoreset = True) as o:
        with mido.open_input() as i:
            while True:
                for message in i:
                    if message.type == 'control_change':## and not message.control == 13:
                        print("in : " + str(message))
                        Translate(message,o)
                        
                    if 'note' in mt:
                        if not pnvalue == nvalue:
                            mo = mido.Message(mt,note = nvalue, velocity = 100)
                            print("out : " + str(mo))
                            o.send(mo)
                            pnvalue = nvalue
                        ##microgranny tends not to respond to off or time, or anything it doesn't like
                        if 'off'in mt:
                            mt = ''
                            o.send(mido.Message('note_off',note = pnvalue))
                            o.send(mido.Message('note_off',note=nvalue))
                            print("out : note_off")
                            o.reset()
                            o.panic()
                            ManualPanic(o)
Exemplo n.º 12
0
    def __init__(self, input=None, output=None):
        if input is None:
            try:
                input = mido.open_input(
                    'Ableton Push User Port',
                    callback=True)
            except IOError:
                input = mido.open_input('Ableton Push MIDI 2', callback=True)
        if output is None:
            try:
                output = mido.open_output('Ableton Push User Port')
            except IOError:
                output = mido.open_output('Ableton Push MIDI 2')

        self.lights = lights((8, 8))
        self.buttons = buttons((8, 8))

        super(Push, self).__init__(input, output)
Exemplo n.º 13
0
    def __init__(self, loop, scale, bpm=120, midi_port=u"TiMidity port 0", midi_chan=1):
        self.loop = loop
        self.scale = scale
        self.bpm = 60 / bpm
        self.start = True

        # initialize midi output
        self.midi_output = mido.open_output(midi_port)
        self.midi_output.send(mido.Message("program_change", program=midi_chan))
Exemplo n.º 14
0
 def __init__(self, input_midi_port, output_midi_port):
   self._inport = mido.open_input(input_midi_port)
   self._outport = mido.open_output(output_midi_port)
   # This lock is used by the serialized decorator.
   self._lock = threading.RLock()
   self._control_cvs = dict()
   self._player = None
   self._capture_start_time = None
   self._sequence_start_time = None
Exemplo n.º 15
0
 def __init__(self):
     QtGui.QWidget.__init__(self)
     try:
         self.output = mido.open_output(self.outputPort)
     except IOError:
         print ("sorry; couldn't setup MIDI player")
         print ("perhapsoverruling outputPort (currently {0} will help".format(self.outputPort))
         self.output = None
     dbg_print('MidiPlayer:__init__', self.output)
Exemplo n.º 16
0
    def __init__(self, daemonize=False, buflen=80):
        self.scrollwheel = 0
        self.buflen = buflen
        self.lines = collections.deque([''] * self.buflen)
        self.lock = threading.Lock()

        try:
            # Ports on MAC OSX
            self.output = mido.open_output('Ableton Push User Port')
            self.input = mido.open_input('Ableton Push User Port',
                                         callback=self.callback)
        except IOError:
            # Ports on Arch Linux
            self.output = mido.open_output('Ableton Push MIDI 2')
            self.input = mido.open_input('Ableton Push MIDI 2',
                                         callback=self.callback)

        while True:
            line = sys.stdin.readline()
            if not line:
                # EOF from STDIN
                break

            # We need to use mutex because concurrent reads and writes on
            # dequeue (scrolling while there is new text coming in from stdin)
            # will issue warnings.
            self.lock.acquire()
            self.lines.append(line)
            self.lines.popleft()
            self.lock.release()
            self.redraw()

        # Do not quit process if running daemonized
        # This enables scrolling for one-show piping to Push
        #
        # e.g. ping www.google.de | pushcat is scrollable as long as ping runs
        # ls | pushcat is not scrollable as ls immediately terminates
        # ls | pushcat -d enables scrolling
        if daemonize:
            while True:
                try:
                    time.sleep(0.1)
                except KeyboardInterrupt:
                    sys.exit(0)
Exemplo n.º 17
0
 def __init__(self, turtle, devname, cb=False):
     self.turtle = turtle
     if cb:
         self.midi_in = mido.open_input(devname, callback=self.midi_callback)
     else:
         self.midi_in = mido.open_input(devname)
     self.midi_out = mido.open_output(devname)
     self.rgb = True
     self.size = 1
     self._update_rgb_indicator()
Exemplo n.º 18
0
def say(message, times = 1):
    message = message + " "
    with mido.open_output(CONTROLLER) as output:
        print("saying \"{}\"".format(message))
        delay = lambda: sleep(0.25)
        for i in range(0,times):
            for frame in text_to_bitmap(message):
                send_lights_to_output(frame, output)
                delay()
            delay()
Exemplo n.º 19
0
Arquivo: mt2.py Projeto: fwilson42/mt2
def open_pair(input, output):
    if not isinstance(input, mido.ports.BaseInput):
        state.inp = mido.open_input([i for i in mido.get_input_names() if i.lower().startswith(input.lower())][0])
    else:
        state.inp = input
    if not isinstance(output, mido.ports.BaseOutput):
        state.out = mido.open_output([i for i in mido.get_output_names() if i.lower().startswith(output.lower())][0])
    else: state.out = output
    setup_threads()
    state.metronome = Metronome()
Exemplo n.º 20
0
  def __init__(self, input_midi_ports, output_midi_ports, texture_type,
               passthrough=True, playback_channel=0, playback_offset=0.0):
    self._texture_type = texture_type
    self._passthrough = passthrough
    self._playback_channel = playback_channel
    self._playback_offset = playback_offset
    # When `passthrough` is True, this is the set of open MIDI note pitches.
    self._open_notes = set()
    # This lock is used by the serialized decorator.
    self._lock = threading.RLock()
    # A dictionary mapping a compiled MidiSignal regex to a condition variable
    # that will be notified when a matching messsage is received.
    self._signals = {}
    # A dictionary mapping a compiled MidiSignal regex to a list of functions
    # that will be called with the triggering message in individual threads when
    # a matching message is received.
    self._callbacks = collections.defaultdict(list)
    # A dictionary mapping integer control numbers to most recently-received
    # integer value.
    self._control_values = {}
    # Threads actively being used to capture incoming messages.
    self._captors = []
    # Potentially active player threads.
    self._players = []
    self._metronome = None

    # Open MIDI ports.

    if input_midi_ports:
      for port in input_midi_ports:
        if isinstance(port, mido.ports.BaseInput):
          inport = port
        else:
          virtual = port not in get_available_input_ports()
          if virtual:
            tf.logging.info(
                "Opening '%s' as a virtual MIDI port for input.", port)
          inport = mido.open_input(port, virtual=virtual)
        # Start processing incoming messages.
        inport.callback = self._timestamp_and_handle_message
    else:
      tf.logging.warn('No input port specified. Capture disabled.')
      self._inport = None

    outports = []
    for port in output_midi_ports:
      if isinstance(port, mido.ports.BaseInput):
        outports.append(port)
      else:
        virtual = port not in get_available_output_ports()
        if virtual:
          tf.logging.info(
              "Opening '%s' as a virtual MIDI port for output.", port)
        outports.append(mido.open_output(port, virtual=virtual))
    self._outport = mido.ports.MultiPort(outports)
Exemplo n.º 21
0
def main():
    with open('a.csv','r') as csvfile:
        reader=csv.reader(csvfile)
        flag=0
        c=0.0
        t0=0
        next(reader)
        next(reader)
        tmp=[(float(x),float(y)) for x,y,z1,z2,z3 in reader]
        timelist,pitchlist=zip(*tmp)
        a=69
        with mido.open_output('LoopBe Internal MIDI') as mid:
            #track=mido.midifiles.MidiTrack()
            #mid.tracks.append(track)
            mid.send(mido.Message('program_change',program=53,time=0.0))
            #pitchlist=butter_lowpass_filter(pitchlist,5,50,5)
            #filtered = scipy.signal.medfilt
            #pitchlist=butter_lowpass_filter(pitchlist,5,100,1)
            #pitchlist=butter_lowpass_filter(pitchlist,5,100,3)
            #if 0:
            for row in list(zip(timelist,pitchlist))[3:-15]:
                row=list(row)
                #print(row)
                b=pitch(float(row[1]))
                if b>100: continue
                if not sticky(b,float(row[1]),a,0.8):
                    if flag:
                        sleep((float(row[0])-t0)/10)
                        mid.send(mido.Message('note_off',note=round(a,0),
                                               time=float(row[0])-t0))
                    else:
                        t0=float(row[0])
                        flag=1
                    t0=float(row[0])                                 
                    #last_state=(2**((round(b,0)-69)/120)*440)
                    print(row[0],int(round(a,0)),int(round(b,0)))
                    a=round(b,0)
                    mid.send(mido.Message('note_on',note=round(b),
                                           time=float(row[0])-t0))
                    
                #timelist.append(float(row[0])-t0)
                #pitchlist.append(float(row[1]))
            #plt.plot(timelist,pitchlist)
            threshold = 0.5
            timelist=np.asarray(timelist[30:])
            pitchlist=np.asarray(pitchlist[30:])
            #deltas = periods(timelist, pitchlist, threshold)
            #print(timelist,pitchlist,deltas)
            plt.plot(timelist,pitchlist)
            #trans_times = butter_lowpass_filter(pitchlist,5,100,3)
            #print(trans_times)
            #plt.plot(timelist,trans_times,'r')
            #plt.plot(trans_times, threshold * np.ones_like(trans_times))
            plt.show()
Exemplo n.º 22
0
        def _sendMidi(note, velocity, length, device):
            velocity = int(round(velocity * 127))
            note = int(note)
            dsp.log(device)
            out = mido.open_output(device)
            msg = mido.Message('note_on', note=note, velocity=velocity)
            out.send(msg)

            dsp.delay(length)

            msg = mido.Message('note_off', note=note, velocity=0)
            out.send(msg)
Exemplo n.º 23
0
 def play(self):
     port_name = 'Microsoft GS Wavetable Synth'    #will need to pick up which port to use when used on different devices
     filename = 'assets/game/enemies/level_1.MID'    #use this to set which level is played
     
     mido.set_backend('mido.backends.pygame')
     with mido.open_output(port_name) as output:
         with MidiFile(filename) as midi_file:
             for message in midi_file.play():
                 if __main__.app.midi_thread.stopped_test():   #checks for stop thread flag
                     break
                 byte_message = message.bytes()
                 self.spawn_enemy(byte_message)
                 output.send(message) 
Exemplo n.º 24
0
	def _open_output(self, port):
		if self._out_port is None:
			try:
				self._out_port = mido.open_output(port)
			except IOError:
				print "Couldn't open output port '%s'. The following MIDI ports are available:" % port
				for p in mido.get_output_names():
					print "'%s'" % p
				raise
		else:
			assert self._out_port.name == port

		return self._out_port
Exemplo n.º 25
0
def initialize_MIDI_out():
    """Initialize a MIDI output port using RTMIDI through mido
    """

    # select rtmidi as our backend
    mido.set_backend('mido.backends.rtmidi')
    # print "Backend selected is %s " % mido.backend

    # Enumerate the available port names
    outports = mido.get_output_names()

    # Now try to pick the right port to output on.
    # If we're in the deployed configuration, it's a MIO adapter, but
    # if we're in the lab, it might be something else.
    # In either event, there might be more than one matching adapter!
    # In that case, we'll punt and take the first one we find.
    out = None
    for name in outports:
        if re.match(r'mio', name):
            try:
                out = mido.open_output(name)
                break
            except:
                pass

    if not out:
        for name in outports:
            try:
                out = mido.open_output(name)
                break
            except:
                pass

    if not out:
        print("Sorry, unable to open any MIDI output port.")
        sys.exit(1)

    return out
Exemplo n.º 26
0
 def __init__(self):
     mido.set_backend('mido.backends.rtmidi')
     try:
         self.outport = mido.open_output('Ableton Push User Port')
     except IOError:
         pass
     self.dialLine = ["","","","","","","",""]
     self.statusLine = {}
     self.modeNames = ["grain", "sample", "loop", "pattern"]
     self.setNetMode(0)
     self.setMidiMode(0)
     self.thread = Thread( target = self.listenToMidi )
     self.thread.start()
     self.currentValues = {}
Exemplo n.º 27
0
 def __init__(self):
     port_names = mido.get_output_names()
     if not port_names:
         raise IndexError("No MIDI output ports found")
     if len(port_names) == 1:
         idx = 0
         logging.info("Choosing MIDI output port %s", port_names[0])
     else:
         print("MIDI output ports:")
         for (idx, name) in enumerate(port_names):
             print("{}. {}".format(idx, name))
         idx = int(raw_input("Which MIDI output port? "))
         assert 0 <= idx < len(port_names)
     self.midi_out = mido.open_output(port_names[idx])
Exemplo n.º 28
0
    def __init__(
        self,
        loop,
        scale,
        x,
        y,
        width=800,
        height=600,
        foreground=(0, 0, 255),
        background=(255, 0, 0),
        midi_port="",
        midi_chan=0,
        bpm=120,
    ):
        self.loop = loop
        self.scale = scale
        self.width = width
        self.height = height
        self.x = x
        self.playhead_x = x
        self.y = y
        self.foreground = foreground
        self.background = background
        self.beat_width = float(width) / len(self.loop)
        self.beat_height = float(height) / len(self.loop[0])
        self.tt = 0
        self.start = True
        self.vertex_index = []
        self.vertex_coords = []
        self.vertex_colors = []
        self.quads = 0
        self.vertexes_from_loop()
        self.bpm = 60 / bpm

        print self.beat_width, self.beat_height

        # initialize midi output
        self.midi_output = mido.open_output(midi_port)
        self.midi_output.send(mido.Message("program_change", program=midi_chan))

        # render SVG
        self.dwg = svgwrite.Drawing(filename="roll.svg", debug=True)

        # load sprites
        self.on = pyglet.image.load("resources/on.png")
        self.on_sprite = pyglet.sprite.Sprite(self.on)

        self.off = pyglet.image.load("resources/off.png")
        self.off_sprite = pyglet.sprite.Sprite(self.off)
Exemplo n.º 29
0
def Run():
    ##start camera and open midi out
    cap = cv2.VideoCapture(0)
    o = mido.open_output(autoreset=True)
    ##then play
    try:
        while True:
            c = camera(cap)
            on = Timer((1/16),play(o,c))
            off = Timer(1,stopAll(o))
    ##ctrl-c to quit, closes camera and midi
    finally:
        cap.release()
        cv2.destroyAllWindows()
        o.close()
Exemplo n.º 30
0
  def __init__(self):
    self.on_button_press = pypush2._utils.events.EventHandler(self)
    '''
    Event raised when a button is pressed.  Handlers should be of the form:

    handler(sender, button)
    '''

    self.on_button_release = pypush2._utils.events.EventHandler(self)
    '''
    Event raised when a button is released.  Handlers should be of the form:

    handler(sender, button)
    '''

    self.on_pad_touch = pypush2._utils.events.EventHandler(self)
    '''
    Event raised when a pad is touched.  Handlers should be of the form:

    handler(sender, padNote, velocity)
    '''

    self.on_pad_release = pypush2._utils.events.EventHandler(self)
    '''
    Event raised when a pad is released.  Handlers should be of the form:

    handler(sender, padNote, velocity)
    '''

    # Encoders not yet implemented--  need further work on the encoder
    # abstraction before they can make sense
    self.on_encoder_touch = pypush2._utils.events.EventHandler(self)
    self.on_encoder_release = pypush2._utils.events.EventHandler(self)
    self.on_encoder_change = pypush2._utils.events.EventHandler(self)

    self.on_unhandled_midi_message = pypush2._utils.events.EventHandler(self)
    '''
    Event raised when a MIDI message is received but isn't handled by
    one of the other event types.  Handlers should be of the form:

    handler(sender, midiMessage)

    where midiMessage is a mido.Message.
    '''
    
    self._midi_input = mido.open_input('Ableton Push 2 Live Port')
    self._midi_output = mido.open_output('Ableton Push 2 Live Port')
Exemplo n.º 31
0
import mido
from rstem.button import Button
from rstem.gpio import Output

output = mido.open_output('X18/XR18 MIDI 1')
button = Button(4)
clean_led = Output(2)
distorted_led = Output(22)

output.send(mido.Message('control_change', channel=1))
output.send(mido.Message('control_change', channel=1, control=1, value=127))
distorted = False
clean_led.on()
distorted_led.off()
while True:
    if button.presses():
        if distorted == True:
            output.send(mido.Message('control_change', channel=1))
            output.send(
                mido.Message('control_change', channel=1, control=1,
                             value=127))
            distorted = False
            clean_led.on()
            distorted_led.off()
        elif distorted == False:
            output.send(mido.Message('control_change', channel=1, value=127))
            output.send(mido.Message('control_change', channel=1, control=1))
            distorted = True
            clean_led.off()
            distorted_led.on()
Exemplo n.º 32
0
import mido
import pigpio

pi1 = pigpio.pi()
outport = mido.open_output('f_midi')  # open USB port

onmess = mido.Message('note_on', note=34, velocity=127)
offmess = mido.Message('note_off', note=34, velocity=127)

buttPin = 21
pi1.set_mode(buttPin, pigpio.INPUT)


def buttonDown(gpio, level, tick):
    print("DOWN")
    #outport.send(onmess)


def buttonUp(gpio, level, tick):
    print("UP")
    #outport.send(offmess)


cb = pi1.callback(buttPin, pigpio.RISING_EDGE, buttonDown)
cb2 = pi1.callback(buttPin, pigpio.FALLING_EDGE, buttonUp)
# Just loop and do nothing
while True:
    pass
Exemplo n.º 33
0
#!/usr/bin/env python3
# From: https://github.com/mido/mido

import mido

mido.open_output("MidiSport 1x1:MidiSport 1x1 MIDI 1 20:0").reset()
Exemplo n.º 34
0
import pygame
import mido
from mido import Message
import os
import numpy as np
import mido.backends.rtmidi

#This version is for use with python 3

#Mido gets the name of all the output ports
print(mido.get_output_names())

#User decides what port to use
userPort = input('Enter the port you would like to use: ')

outport = mido.open_output(userPort)

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

#This is for a wider controller support
safeCheck1 = 0
safeCheck2 = 0


#This function is what determines when to play which note from which button
#button_was_pressed is equal to 0 when it has gone two frames without being pressed.
#It is equal to 1 when it has gone one frame without being pressed.
#And equal to two when it is pressed.
def signalOnPress(note1, button1):
Exemplo n.º 35
0
print('------ OUTPUT ------')
for port in mido.get_output_names():
  print(port)
print('-------------------------')

mididevice = patch.getstring('midi', 'device')
try:
    inputport  = mido.open_input(mididevice)
    if debug>0:
        print "Connected to MIDI input"
except:
    print "Error: cannot connect to MIDI input"
    exit()

try:
    outputport  = mido.open_output(mididevice)
    if debug>0:
        print "Connected to MIDI output"
except:
    print "Error: cannot connect to MIDI output"
    exit()

try:
    # channel 1-16 in the ini file should be mapped to 0-15
    midichannel = patch.getint('midi', 'channel')-1
except:
    # this happens if it is not specified in the ini file
    # it will be determined on the basis of the first incoming message
    midichannel = None

# the input scale and offset are used to map Redis values to MIDI values
Exemplo n.º 36
0
def PerCon():
    global pc
    global ch
    global ton
    while True:
        # Song start
        if GPIO.input(5) == 0:
            with mido.open_output("USB MIDI Interface MIDI 1") as outport:
                time.sleep(0.5)
                outport.send(
                    mido.Message('note_on', channel=15, note=27, velocity=65))
                print('Song Start')

# Song Stopp
        if GPIO.input(22) == 0:
            with mido.open_output("USB MIDI Interface MIDI 1") as outport:
                time.sleep(0.5)
                outport.send(
                    mido.Message('note_on', channel=15, note=28, velocity=65))
                print('Song Stopp')

# PC = 1
        if GPIO.input(27) == 0:
            time.sleep(0.5)
            ch = 0
            pc = 1
            PC()
# PC = 2
        if GPIO.input(17) == 0:
            time.sleep(0.5)
            ch = 0
            pc = 2
            PC()
# PC = 3
        if GPIO.input(4) == 0:
            time.sleep(0.5)
            ch = 0
            pc = 3
            PC()
# PC = 4
        if GPIO.input(12) == 0:
            time.sleep(0.5)
            ch = 0
            pc = 4
            PC()
# PC = 5
        if GPIO.input(25) == 0:
            time.sleep(0.5)
            ch = 0
            pc = 5
            PC()
# PC = 6
        if GPIO.input(24) == 0:
            time.sleep(0.5)
            ch = 0
            pc = 6
            PC()
# PC = 7
        if GPIO.input(23) == 0:
            with mido.open_output("USB MIDI Interface MIDI 1") as outport:
                time.sleep(0.5)
                outport.send(
                    mido.Message('note_on', channel=15, note=9, velocity=65))
                print('All Notes Off')
# PC = 8
        if GPIO.input(18) == 0:
            global ton
            time.sleep(0.5)
            if ton == True:
                with mido.open_output("USB MIDI Interface MIDI 1") as outport:
                    outport.send(
                        mido.Message('control_change',
                                     channel=0,
                                     control=64,
                                     value=127))
                print('Damper on')
                ton = not ton
            else:
                with mido.open_output("USB MIDI Interface MIDI 1") as outport:
                    outport.send(
                        mido.Message('control_change',
                                     channel=0,
                                     control=64,
                                     value=0))
                print('Damper off')
                ton = not ton
 def stop(self, instance):
     Clock.unschedule(play_loop)
     outport = mido.open_output('HDSPMx73554b MIDI 3')
     stop_msg = mido.Message('sysex', data=[127, 127, 6, 1])
     outport.send(stop_msg)
Exemplo n.º 38
0
import mido
import time
import math

ports = mido.get_output_names()
print(ports)
port_name = ''
# find the PyBadge port
for item in ports:
    if item[:7] == 'PyBadge':
        port_name = item
        break

if port_name != '':
    print('Opening port: ' + port_name)
    port = mido.open_output(port_name)
    counter = 0
    start = True
    bpm = 60
    ppq = 24
    beat_ms = math.floor(60000 / (bpm * ppq))
    beat_seconds = beat_ms / 1000
    print('BPM: ' + str(bpm))
    print('beat_ms: ' + str(beat_ms))
    print('beat_seconds: ' + str(beat_seconds))
    while True:
        counter += 1
        msg = mido.Message('clock')
        port.send(msg)
        time.sleep(beat_seconds)
Exemplo n.º 39
0
    def __init__(self,
                 input_midi_ports,
                 output_midi_ports,
                 texture_type,
                 passthrough=True,
                 playback_offset=0.0):
        self._texture_type = texture_type
        self._passthrough = passthrough
        self._playback_offset = playback_offset
        # When `passthrough` is True, this is the set of open MIDI note
        # pitches.
        self._open_notes = set()
        # This lock is used by the serialized decorator.
        self._lock = threading.RLock()
        # A dictionary mapping a compiled MidiSignal regex to a condition variable
        # that will be notified when a matching messsage is received.
        self._signals = {}
        # A dictionary mapping a compiled MidiSignal regex to a list of functions
        # that will be called with the triggering message in individual threads when
        # a matching message is received.
        self._callbacks = defaultdict(list)
        # A dictionary mapping integer control numbers to most recently-received
        # integer value.
        self._control_values = {}
        # Threads actively being used to capture incoming messages.
        self._captors = []
        # Potentially active player threads.
        self._players = []
        self._metronome = None

        # Open MIDI ports.

        if input_midi_ports:
            for port in input_midi_ports:
                if isinstance(port, ports.BaseInput):
                    inport = port
                else:
                    virtual = port not in get_input_names()
                    if virtual:
                        logging.info(
                            "Opening '%s' as a virtual MIDI port for input.",
                            port)
                    inport = open_input(port, virtual=virtual)
                # Start processing incoming messages.
                inport.callback = self._timestamp_and_handle_message
                # this is needed because otherwise inport will get
                # garbage collected and stop receiving input events
                self._inport = inport
        else:
            logging.warning('No input port specified. Capture disabled.')
            self._inport = None

        outports = []
        for port in output_midi_ports:
            if isinstance(port, ports.BaseInput):
                outports.append(port)
            else:
                virtual = port not in get_output_names()
                if virtual:
                    logging.info(
                        "Opening '%s' as a virtual MIDI port for output.",
                        port)
                outports.append(open_output(port, virtual=virtual))
        self._outport = ports.MultiPort(outports)
Exemplo n.º 40
0
 def applyPort(self):
     self.currentPort = self.port
     self.outport.close()
     self.outport = mido.open_output(self.currentPort.get())
Exemplo n.º 41
0
    def __init__(self, master, config):
        # Sets up main window and global config.
        self.window = master
        self.config = config
        master.title("Cooltrollers")
        #master.iconbitmap(default="controller.ico")

        # Adds menus.
        menuBar = Menu(master)
        fileMenu = Menu(menuBar, tearoff=0)
        optionsMenu = Menu(menuBar, tearoff=0)
        menuBar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(
            label="Controller",
            command=lambda: Controller(self.outport, self.config, self.
                                       instruString, self.window))
        fileMenu.add_command(label="Exit", command=sys.exit)
        menuBar.add_cascade(label="Options", menu=optionsMenu)
        optionsMenu.add_command(label="Button Manager",
                                command=self.buttonManager)
        optionsMenu.add_command(label="Controller Manager",
                                command=self.controllerManager)
        master.config(menu=menuBar)
        master.resizable(0, 0)

        # Initializes mido, the MIDI outport, and global variables that are used in functionality().
        midi_out = mido.get_output_names()
        self.octave = 0
        self.counter = -1

        # Sets up octave display. Every time it's changed via + or -, the display updates accordingly (via statements in functionality())
        self.currentOctaveText = StringVar()
        self.currentOctaveText.set("Current octave: {0}".format(
            int((self.octave / 12) + 4)))
        octaveDisplay = Label(master,
                              textvariable=self.currentOctaveText,
                              anchor=NE)
        octaveDisplay.grid(row=0, columnspan=2)

        # Any key that's pressed activates functionality(), which plays notes.
        master.bind("<Key>", self.functionality)

        # Combo box and apply button for selecting MIDI port.
        self.port = StringVar(master)
        self.port.set(midi_out[0])
        self.currentPort = self.port
        portSelect = OptionMenu(master, self.port, *midi_out)
        portSelect.grid(row=1)
        applyPortButton = Button(master, text="Apply", command=self.applyPort)
        applyPortButton.grid(row=1, column=1)
        self.outport = mido.open_output(self.currentPort.get())

        # Setting up proper binding settings for playback.
        # This right here is all the General MIDI instruments in one list.
        self.instruList = [
            '1 Acoustic Grand Piano', '2 Bright Acoustic Piano',
            '3 Electric Grand Piano', '4 Honky-tonk Piano',
            '5 Electric Piano 1', '6 Electric Piano 2', '7 Harpsichord',
            '8 Clavinet', '9 Celesta', '10 Glockenspiel', '11 Music Box',
            '12 Vibraphone', '13 Marimba', '14 Xylophone', '15 Tubular Bells',
            '16 Dulcimer', '17 Drawbar Organ', '18 Percussive Organ',
            '19 Rock Organ', '20 Church Organ', '21 Reed Organ',
            '22 Accordion', '23 Harmonica', '24 Tango Accordion',
            '25 Acoustic Guitar (nylon)', '26 Acoustic Guitar (steel)',
            '27 Electric Guitar (jazz)', '28 Electric Guitar (clean)',
            '29 Electric Guitar (muted)', '30 Overdriven Guitar',
            '31 Distortion Guitar', '32 Guitar harmonics', '33 Acoustic Bass',
            '34 Electric Bass (finger)', '35 Electric Bass (pick)',
            '36 Fretless Bass', '37 Slap Bass 1', '38 SlapBass 2',
            '39 Synth Bass 1', '40 Synth Bass 2', '41 Violin', '42 Viola',
            '43 Cello', '44 Contrabass', '45 Tremolo Strings',
            '46 Pizzicato Strings', '47 Orchestral Harp', '48 Timpani',
            '49 String Ensemble 1', '50 String Ensemble 2',
            '51 Synth Strings 1', '52 Synth Strings 2', '53 Choir Aahs',
            '54 Voice Oohs', '55 Synth Voice', '56 Orchestra Hit',
            '57 Trumpet', '58 Trombone', '59 Tuba', '60 Muted Trumpet',
            '61 French Horn', '62 Brass Section', '63 Synth Brass 1',
            '64 Synth Brass 2', '65 Soprano Sax', '66 Alto Sax',
            '67 Tenor Sax', '68 Baritone Sax', '69 Oboe', '70 English Horn',
            '71 Bassoon', '72 Clarinet', '73 Piccolo', '74 Flute',
            '75 Recorder', '76 Pan Flute', '77 Blown Bottle', '78 Shakuhachi',
            '79 Whistle', '80 Ocarina', '81 Lead 1 (square)',
            '82 Lead 2 (sawtooth)', '83 Lead 3 (calliope)',
            '84 Lead 4 (chiff)', '85 Lead 5 (charang)', '86 Lead 6 (voice)',
            '87 Lead 7 (fifths)', '88 Lead 8 (bass + lead)',
            '89 Pad 1 (new age)', '90 Pad 2 (warm)', '91 Pad 3 (polysynth)',
            '92 Pad 4 (choir)', '93 Pad 5 (bowed)', '94 Pad 6 (metallic)',
            '95 Pad 7 (halo)', '96 Pad 8 (sweep)', '97 FX 1 (rain)',
            '98 FX 2 (soundtrack)', '99 FX 3 (crystal)',
            '100 FX 4 (atmosphere)', '101 FX 5 (brightness)',
            '102 FX 6 (goblins)', '103 FX 7 (echoes)', '104 FX 8 (sci-fi)',
            '105 Sitar', '106 Banjo', '107 Shamisen', '108 Koto',
            '109 Kalimba', '110 Bag pipe', '111 Fiddle', '112 Shanai',
            '113 Tinkle Bell', '114 Agogo', '115 Steel Drums', '116 Woodblock',
            '117 Taiko Drum', '118 Melodic Tom', '119 Synth Drum',
            '120 Reverse Cymbal', '121 Guitar Fret Noise', '122 Breath Noise',
            '123 Seashore', '124 Bird Tweet', '125 Telephone Ring',
            '126 Helicopter', '127 Applause', '128 Gunshot'
        ]

        # Checks whether there's a settings file. Otherwise, the user must set up button binds in the bind manager.
        if (os.path.isfile('settings.ini')):
            self.config.read('settings.ini')
            keyString = self.config.get('Button Binds', 'Keys')
            instrumentString = self.config.get('Button Binds', 'Instruments')
            noteString = self.config.get('Button Binds', 'Notes')
            self.key = keyString.split(",")
            self.instruString = instrumentString.split(",")
            self.note = noteString.split(",")

            buttonString = self.config.get('Joystick Binds', 'Buttons')
            btnInstrumentString = self.config.get('Joystick Binds',
                                                  'Instruments')
            btnNoteString = self.config.get('Joystick Binds', 'Notes')
            self.button = buttonString.split(",")
            self.btnInstruString = btnInstrumentString.split(",")
            self.btnNote = btnNoteString.split(",")

            for x in range(16):
                self.button[x] = int(self.button[x])

        else:
            # Config file initial setup. Uses strings with commas separating list items to store in the file.
            self.clearBinds()
            self.clearCtrlBinds()
Exemplo n.º 42
0
#!/usr/bin/env python3
# From: https://github.com/mido/mido

import mido
import time
import subprocess, signal, os

# See what ports are out there
# print(mido.get_output_names())
# print(mido.get_input_names())

organ = "MidiSport 1x1:MidiSport 1x1 MIDI 1 20:0"
outport = mido.open_output(organ)

mypath = 'midifiles'

from os import listdir
from os.path import isfile, join

files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
offset = 3  # Number of tabs in to start

files.sort()
print(files)
print(len(files))


def lightsOn(count):
    print("Sending cancel")
    msg = mido.Message('sysex', data=[0, 74, 79, 72, 65, 83, 127])
    outport.send(msg)
                        type=int,
                        default=9997,
                        help="The port for server listen on")
    parser.add_argument("--clientport",
                        type=int,
                        default=9996,
                        help="The client port")
    parser.add_argument(
        "--datafile",
        default="fretdata.p",
        help="File to write data to (extension should be '.p')")
    parser.add_argument("--max_notes_per_chord", type=int, default=6)
    parser.add_argument("--midi_port", default='IAC Driver Bus 1')
    args = parser.parse_args()
    try:
        midiout = mido.open_output(args.midi_port)
    except:
        print("The midi port {} could not be found".format(args.midi_port))
        print(
            "To run with a different midi port, rerun this program with the command line"
            + "argument '--midi_port 'port name goes here' ")
        print(
            "Where 'port name goes here' corresponds to one of the following recognized midi ports:"
        )
        print(mido.get_output_names())
        sys.exit()

    guitar_notes = create_notebins(min_note='E2', max_note='C#6')
    NONZERO_COEFS = args.max_notes_per_chord
    datafilename = args.datafile
    dispatcher = dispatcher.Dispatcher()
Exemplo n.º 44
0
from __future__ import print_function

import sys
from DeepSymphony.utils import Song
import mido

if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.argv.append('simple_rnn.mid')
    song = Song(sys.argv[1])

    # run `timidity -iA` to open the daemon synthesizer
    # use port to send message to the daemon synthesizer

    port = mido.open_output(name='TiMidity port 0')
    keyboard = ['_'] * 128
    for msg in song.playback():
        if msg.type == 'note_on':
            keyboard[msg.note] = '^'
        elif msg.type == 'note_off':
            keyboard[msg.note] = '_'
        print(''.join(keyboard), end='\r')
        sys.stdout.flush()

        port.send(msg)
Exemplo n.º 45
0
                              text=True).stdout
    temp_decimal = temp_str.split('.')[1][0]
    return int(temp_decimal)


if __name__ == "__main__":

    sensor_list = [temperature_note_test
                   ]  # A list of functions that return a value in sensor_list

    # We'll need to store channel state. Initialising to nonsense.
    frozen_msg = mido.Message('note_off')
    last_msgs_sent = [frozen_msg] * len(sensor_list)

    # Set up Midi outputs
    out = mido.open_output('UM-ONE:UM-ONE MIDI 1 20:0')

    # Now and forever more, do things.
    while 1 == 1:
        # Poll sensors
        for channel, sensor in enumerate(sensor_list):
            reading = sensor()

            print("Sensor {} reading = {}".format(sensor, reading))

            # Kill last note (for now, we're assuming that we only control note with sensor)
            print("Note off on channel {}".format(channel))
            last_note = last_msgs_sent[channel].note
            msg = Message('note_off', note=last_note, channel=channel)
            out.send(msg)
Exemplo n.º 46
0
 def __init__(self, control_channel=1, midi_out_name=False):
     if midi_out_name is False:
         self._port = mido.open_output('video2midi', virtual=True)
     else:
         self._port = mido.open_output(midi_out_name)
     self.set_control_channel(control_channel)
Exemplo n.º 47
0
import pygame
import mido
from mido import Message
import os
import mido.backends.rtmidi

#This version is for use with python 2

button_was_pressed = False
print(mido.get_output_names())
outport = mido.open_output("lport 3")

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# This is a simple class that will help us print to the screen
# It has nothing to do with the joysticks, just outputting the
# information.
'''
class TextPrint:
    def __init__(self):
        self.reset()
        self.font = pygame.font.Font(None, 20)

    def print(self, screen, textString):
        textBitmap = self.font.render(textString, True, BLACK)
        screen.blit(textBitmap, [self.x, self.y])
        self.y += self.line_height
        
    def reset(self):
Exemplo n.º 48
0
                        )
                        chord_progression.insert(0, note_queue)
                        note_queue = []
                        return
                    print('computer should not record.')
                    computer_should_record = False
                    time_since_pedal_released = time.time()
                else:
                    pass


input_name = mido.get_input_names()[0]
input_port = mido.open_input(input_name, callback=handle_message)

output_name = mido.get_output_names()[0]
output_port = mido.open_output(output_name)


def main():
    global note_queue
    global input_port
    global output_port
    global computer_should_record
    global init_time
    global last_time

    while not init:
        time.sleep(0.1)

    init_time = time.time()
    print("Record!")
Exemplo n.º 49
0
 def __init__(self, binding):
     self.port = mido.open_output(binding.midi_port_name)
Exemplo n.º 50
0
wait = False  #PAUSE FOR WHEN NOTE DROPS TOO FAR
#mapping = {:1,:2,:3,:4,60:5,:6,:7,:8,:9,:10}
notespeed = 5  #speed at which notes fall/rise
'''FIRE UP TiMIDIty++'''
'''def starttimidity():
    os.system('timidity -iAqq')

def startstarttimidity():
    timiditythread = Thread(target = starttimidity)
    timiditythread.daemon = True
    timiditythread.start()

startstarttimidity()'''

mido.set_backend('mido.backends.pygame')
port = mido.open_output(mido.get_output_names()[1])
pygame.init()
'''TITLESCREENS'''


def readtitle():
    global screenw, screenh, screen
    while True:
        screen.fill((0, 0, 0))
        titlefont = pygame.font.Font(None, 300)
        normalfont = pygame.font.Font(None, 100)
        screen.blit(titlefont.render('Learn', 1, (100, 100, 100)),
                    (screenw * 0.1 + 20, screenh * 0.25 + 20))
        screen.blit(titlefont.render('Learn', 1, (100, 255, 100)),
                    (screenw * 0.1, screenh * 0.25))
        pygame.display.flip()
Exemplo n.º 51
0
    print("\nprogram exiting gracefully")
    midiout.close()
    sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)

# here we're printing the ports to check that we see the one that loopMidi created.
# In the list we should see a port called "loopMIDI port".

midi_connected = False

for i, port in enumerate(available_ports):
    if midiportname in port:
        print('Connecting to midi port: ' + port)
        midiout = port = mido.open_output(port)
        midi_connected = True

if not midi_connected:
    print('Could not find port ' + midiportname + ' in following midi ports')
    print(available_ports)

if args.no_osc:
    osc_client = None
else:
    osc_client = udp_client.SimpleUDPClient(args.ip, args.port)

import json
with open('ranges_dict.json', 'r') as f:
    cube_ranges = json.load(f)
Exemplo n.º 52
0
import pyaudio
import audioop
import mido

mido.set_backend('mido.backends.rtmidi')

output = mido.open_output()

# CHUNK = 256
CHUNK = 1024

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 50 # set for how many seconds it is active
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

maxRMS = 8000 # adjust according to the input device used, noise etc.
lastMax = 0
maxMIDI = 0

averageLast = []
maxAvgLast = 50

def retAverage(last):

    global averageLast

    if len(averageLast) == maxAvgLast:
Exemplo n.º 53
0
def main_app(offline: bool):
    global_storage = GlobalStorage()
    sm = None
    aq = None
    ae = None
    if not offline:
        sm = SimConnect()
        aq = AircraftRequests(sm, _time=200)
        ae = AircraftEvents(sm)
        global_storage.set_aircraft_events(ae)
        global_storage.set_aircraft_requests(aq)
    else:
        global_storage.set_aircraft_events(MockAircraftEvents())
        global_storage.set_aircraft_requests(MockAircraftRequests())

    print('Midi input devices:', mido.get_input_names())
    print('Midi output devices:', mido.get_output_names())
    selected_input = ConfigFile.get_midi_input()
    selected_output = ConfigFile.get_midi_output()
    print('Using midi input device:', selected_input)
    print('Using midi output device:', selected_output)

    aircraft = aq.get('TITLE')
    print("Current aircraft:", aircraft)
    outport = mido.open_output(selected_output)  # pylint: disable=no-member

    control_change_dict = {}
    note_dict = {}

    def handle_message(msg: mido.Message):
        # print(msg)
        if msg.type == 'control_change':
            if msg.control in control_change_dict:
                control_change_dict[msg.control].on_cc_data(msg.value)
        elif msg.type == 'note_on':
            if msg.note in note_dict:
                note_dict[msg.note].on_note_data(True)
        elif msg.type == 'note_off':
            if msg.note in note_dict:
                note_dict[msg.note].on_note_data(False)

    inport = mido.open_input(selected_input, callback=handle_message)  # pylint: disable=no-member

    for e in range(1, 17):
        encoder = RotaryEncoder(e, outport)
        global_storage.add_encoder(encoder)

    for b in range(1, 33):
        btn = PushButton(b, outport)
        global_storage.add_button(btn)

    for f in range(1, 3):
        fader = Fader(f)
        global_storage.add_fader(fader)

    c = ConfigFile(aircraft)
    c.configure()
    triggers = c.triggers

    for encoder in GlobalStorage().encoders:
        control_change_dict[encoder.rotary_control_channel] = encoder
        note_dict[encoder.button_note] = encoder

    for btn in GlobalStorage().buttons:
        note_dict[btn.button_note] = btn

    for f in GlobalStorage().faders:
        control_change_dict[f.control_channel] = f

    while True:
        for obj in GlobalStorage().all_elements:
            if obj.bound_simvar and aq:
                sv = aq.get(obj.bound_simvar)
                obj.on_simvar_data(sv)

        current_aircraft = aq.get('TITLE')
        if current_aircraft and aircraft != current_aircraft:
            print("Aircraft changed from", aircraft, "to", current_aircraft)
            break
        time.sleep(0.05)

    global_storage.clear()
    inport.close()
    outport.close()
Exemplo n.º 54
0
def _start():
    '''Start the module
    This uses the global variables from setup and adds a set of global variables
    '''
    global parser, args, config, r, response, patch, name
    global debug, mididevice, port, previous_note, UpdateVelocity, UpdateDuration, TriggerThread, trigger_name, trigger_code, code, trigger, this, thread, control_name, control_code, previous_val, SetNoteOff, SetNoteOn, duration_note, lock, midichannel, monitor, monophonic, offset_duration, offset_velocity, outputport, scale_duration, scale_velocity, sendMidi, velocity_note

    # this can be used to show parameters that have changed
    monitor = EEGsynth.monitor(name=name,
                               debug=patch.getint('general', 'debug'))

    # get the options from the configuration file
    debug = patch.getint('general', 'debug')
    monophonic = patch.getint('general', 'monophonic', default=1)
    midichannel = patch.getint(
        'midi', 'channel') - 1  # channel 1-16 get mapped to 0-15
    mididevice = patch.getstring('midi', 'device')
    mididevice = EEGsynth.trimquotes(mididevice)
    mididevice = process.extractOne(
        mididevice, mido.get_output_names())[0]  # select the closest match

    # values between 0 and 1 work well for the note duration
    scale_duration = patch.getfloat('scale', 'duration', default=1)
    offset_duration = patch.getfloat('offset', 'duration', default=0)
    # values around 64 work well for the note velocity
    scale_velocity = patch.getfloat('scale', 'velocity', default=1)
    offset_velocity = patch.getfloat('offset', 'velocity', default=0)

    # this is only for debugging, and to check which MIDI devices are accessible
    monitor.info('------ INPUT ------')
    for port in mido.get_input_names():
        monitor.info(port)
    monitor.info('------ OUTPUT ------')
    for port in mido.get_output_names():
        monitor.info(port)
    monitor.info('-------------------------')

    try:
        outputport = mido.open_output(mididevice)
        monitor.success('Connected to MIDI output')
    except:
        raise RuntimeError("cannot connect to MIDI output")

    # this is to prevent two messages from being sent at the same time
    lock = threading.Lock()

    previous_note = None
    velocity_note = None
    duration_note = None

    def UpdateVelocity():
        global velocity_note
        velocity_note = patch.getfloat('velocity', 'note', default=64)
        velocity_note = int(
            EEGsynth.rescale(velocity_note,
                             slope=scale_velocity,
                             offset=offset_velocity))

    def UpdateDuration():
        global duration_note
        duration_note = patch.getfloat('duration', 'note', default=None)
        if duration_note != None:
            duration_note = EEGsynth.rescale(duration_note,
                                             slope=scale_duration,
                                             offset=offset_duration)
            # some minimal time is needed for the duration
            duration_note = EEGsynth.limit(duration_note, 0.05, float('Inf'))

    # call them once at the start
    UpdateVelocity()
    UpdateDuration()

    trigger_name = []
    trigger_code = []
    for code in range(1, 128):
        trigger_name.append("note%03d" % code)
        trigger_code.append(code)
        trigger_name.append("control%03d" % code)
        trigger_code.append(code)
        trigger_name.append("polytouch%03d" % code)
        trigger_code.append(code)
    for name in [
            'note', 'aftertouch', 'pitchwheel', 'start', 'continue', 'stop',
            'reset'
    ]:
        trigger_name.append(name)
        trigger_code.append(None)

    # each of the Redis messages is mapped onto a different MIDI message
    trigger = []
    for name, code in zip(trigger_name, trigger_code):
        if config.has_option('trigger', name):
            # start the background thread that deals with this note
            this = TriggerThread(patch.getstring('trigger', name), name, code)
            trigger.append(this)
            monitor.debug(name, 'trigger configured')

    # start the thread for each of the triggers
    for thread in trigger:
        thread.start()

    control_name = []
    control_code = []
    for code in range(1, 128):
        control_name.append("note%03d" % code)
        control_code.append(code)
        control_name.append("control%03d" % code)
        control_code.append(code)
        control_name.append("polytouch%03d" % code)
        control_code.append(code)
    for name in [
            'note', 'aftertouch', 'pitchwheel', 'start', 'continue', 'stop',
            'reset'
    ]:
        control_name.append(name)
        control_code.append(None)

    # control values are only interesting when different from the previous value
    previous_val = {}
    for name in control_name:
        previous_val[name] = None

    # there should not be any local variables in this function, they should all be global
    if len(locals()):
        print('LOCALS: ' + ', '.join(locals().keys()))
Exemplo n.º 55
0
        sleep(0.8)


def on_screen_ready(screen):
    from threading import Thread
    ui_thread = Thread(target=demo, args=(screen, ))
    ui_thread.start()


### MAIN PROGRAM ######

#MIDI output print_ports
print_ports('Output Ports:', mido.get_output_names())
names = mido.get_output_names()
print(names[1])
port = mido.open_output(names[1])

#COINMARKET credentials
session = Session()
session.headers.update(headers)

#block count
r = requests.get("https://blockchain.info/q/getblockcount")
#print("Block Count: ", r.content.decode("utf-8"))
blockCount = r.content.decode("utf-8")  # global variable for displaying

#get Bitcoin info at the beginning
threading.Thread(target=updateBitcoin).start()

#parallel processes
#threading.Thread(target=transactions).start()
Exemplo n.º 56
0
from __future__ import print_function
import sys
import time
import random
import mido
from mido import Message

if len(sys.argv) > 1:
    portname = sys.argv[1]
else:
    portname = None  # Use default port

# A pentatonic scale
notes = [60, 62, 64, 67, 69, 72]

with mido.open_output(portname, autoreset=True) as port:
    print('Using {}'.format(port))
    while 1:
        note = random.choice(notes)

        on = Message('note_on', note=note)
        print('Sending {}'.format(on))
        port.send(on)
        time.sleep(0.05)

        off = Message('note_off', note=note)
        print('Sending {}'.format(off))
        port.send(off)
        time.sleep(0.1)

print()
Exemplo n.º 57
0
def _loop_once():
    """Run the main loop once
    This uses the global variables from setup and start, and adds a set of global variables
    """
    global parser, args, config, r, response, patch
    global monitor, stepsize, scale_rate, offset_rate, scale_shift, offset_shift, scale_ppqn, offset_ppqn, lock, clock, i, clockthread, midithread, redisthread, midiport, previous_midi_play, previous_midi_start, previous_redis_play
    global start, redis_play, midi_play, midi_start, rate, shift, ppqn, elapsed, naptime

    redis_play = patch.getint('redis', 'play')
    midi_play = patch.getint('midi', 'play')
    midi_start = patch.getint('midi', 'start')

    if previous_redis_play is None and redis_play is not None:
        previous_redis_play = not (redis_play)

    if previous_midi_play is None and midi_play is not None:
        previous_midi_play = not (midi_play)

    if previous_midi_start is None and midi_start is not None:
        previous_midi_start = not (midi_start)

    # the MIDI port should only be opened once, and only if needed
    if midi_play and midiport == None:
        mididevice = patch.getstring('midi', 'device')
        mididevice = EEGsynth.trimquotes(mididevice)
        mididevice = process.extractOne(
            mididevice, mido.get_output_names())[0]  # select the closest match
        try:
            outputport = mido.open_output(mididevice)
            monitor.success('Connected to MIDI output')
        except:
            raise RuntimeError("cannot connect to MIDI output")

    # do something whenever the value changes
    if redis_play and not previous_redis_play:
        redisthread.setEnabled(True)
        previous_redis_play = True
    elif not redis_play and previous_redis_play:
        redisthread.setEnabled(False)
        previous_redis_play = False

    # do something whenever the value changes
    if midi_play and not previous_midi_play:
        midithread.setEnabled(True)
        previous_midi_play = True
    elif not midi_play and previous_midi_play:
        midithread.setEnabled(False)
        previous_midi_play = False

    # do something whenever the value changes
    if midi_start and not previous_midi_start:
        if midiport != None:
            midiport.send(mido.Message('start'))
        previous_midi_start = True
    elif not midi_start and previous_midi_start:
        if midiport != None:
            midiport.send(mido.Message('stop'))
        previous_midi_start = False

    rate = patch.getfloat('input', 'rate', default=0)
    rate = EEGsynth.rescale(rate, slope=scale_rate, offset=offset_rate)
    rate = EEGsynth.limit(rate, 30., 240.)

    shift = patch.getfloat('input', 'shift', default=0)
    shift = EEGsynth.rescale(shift, slope=scale_shift, offset=offset_shift)
    shift = int(shift)

    ppqn = patch.getfloat('input', 'ppqn', default=0)
    ppqn = EEGsynth.rescale(ppqn, slope=scale_ppqn, offset=offset_ppqn)
    ppqn = find_nearest_value([1, 2, 3, 4, 6, 8, 12, 24], ppqn)

    # show the parameters whose value has changed
    monitor.update("redis_play", redis_play)
    monitor.update("midi_play", midi_play)
    monitor.update("midi_start", midi_start)
    monitor.update("rate", rate)
    monitor.update("shift", shift)
    monitor.update("ppqn", ppqn)

    # update the clock and redis
    clockthread.setRate(rate)
    redisthread.setShift(shift)
    redisthread.setPpqn(ppqn)

    # there should not be any local variables in this function, they should all be global
    if len(locals()):
        print("LOCALS: " + ", ".join(locals().keys()))
Exemplo n.º 58
0
import rtmidi_python as rtmidi
import time

from pygame import *
from mido import *
from mido import Message

import mido
import pygame
import time

mido.set_backend("mido.backends.pygame")
names = mido.get_output_names()
print names

outport = mido.open_output(names[3])

if (len(argv) < 3):
    print("Usage- python %s COM_PORT note1 [note2 note3 ...]" % (argv[0]))
    exit(0)

notes = []
for note in argv[2:]:  # append all notes (params) passed in command line
    notes.append(note)
print "Notes- " + str(notes)

com_port = argv[1]
print "Using COM port- " + com_port
ser = serial.Serial(com_port, 9600)
#ser.reset_input_buffer()
Exemplo n.º 59
0
def main():

    #Get options from input
    parser = argparse.ArgumentParser(
        description='Superpermutation to midi converter')
    parser.add_argument(
        'inputfile',
        help='The file containing the superpermutation to convert.')
    parser.add_argument('outputfile',
                        nargs='?',
                        default='inputfile',
                        help='The file to store the midi output in.')
    parser.add_argument(
        '-s',
        '--scale',
        nargs='?',
        default="default",
        help='Scale to translate the numbers into. Possible scales:\
                          major, natural-minor, harmonic-minor, whole-note')
    parser.add_argument(
        '-p',
        '--play',
        action='store_true',
        help=
        'Play back the midifile when running the script(requires python-rtmidi)'
    )
    parser.add_argument(
        '-I',
        '--instrument',
        default=46,
        help='General MIDI instrument number from 0 to 127. Default: 46 (harp)'
    )
    parser.add_argument('-l',
                        '--note_length',
                        default='edge-weight',
                        help='The method to decide note lengths.\
                          Possible values are: edge-weight, free-space, even')

    args = parser.parse_args()

    input_string = open(args.inputfile, 'r').read().strip()
    superpermutation = np.array(list(input_string), dtype=int)
    #Make sure it is zero indexed
    superpermutation -= superpermutation.min()

    N = superpermutation.max() + 1

    note_lengths = np.zeros_like(superpermutation)

    scale = args.scale
    if args.scale == "default":
        if N == 7:
            scale = "major"
        elif N == 6:
            scale = "whole-note"
        elif N == 5:
            scale = "major-pentatonic"

    scaleFunction = {
        "major": partial(numberToScale, scale=Scales.major),
        "natural-minor": partial(numberToScale, scale=Scales.natural_minor),
        "harmonic-minor": partial(numberToScale, scale=Scales.harmonic_minor),
        "whole-note": partial(numberToScale, scale=Scales.whole_note),
        "major-pentatonic": partial(numberToScale,
                                    scale=Scales.major_pentatonic),
        "miyako-bushi": partial(numberToScale, scale=Scales.miyako_bushi)
    }.get(scale, "major")

    if args.note_length == 'free-space':
        for i, number in enumerate(superpermutation):
            num_perms = 0

            # Length based on how far it is to the same value on both sides
            for j in range(1, N):
                if i - j < 0 or superpermutation[i - j] == number:
                    break
                num_perms += 1
            for j in range(1, N):
                if i + j >= superpermutation.size or superpermutation[
                        i + j] == number:
                    break
                num_perms += 1
            note_lengths[i] = num_perms - N + 1

    elif args.note_length == 'edge-weight':
        for i, number in enumerate(superpermutation):
            weight = 0
            for j in range(i + 1, i + N + 1):
                if j >= N and j < superpermutation.size:
                    if isLegalPermutation(superpermutation[j - N:j]):
                        break
                weight += 1

            note_lengths[i] = N - weight - 1
    else:
        note_lengths[:] = N - 1

    # Fix the end values
    note_lengths[0:N - 1] = N - 1

    mid = MidiFile()
    track = MidiTrack()
    mid.tracks.append(track)

    track.append(Message('program_change', program=args.instrument, time=0))

    for i in range(superpermutation.size):
        note = scaleFunction(superpermutation[i])

        track.append(Message('note_on', note=note, time=0))
        track.append(
            Message('note_off', note=note, time=2**(note_lengths[i] + 10 - N)))

    if args.outputfile == "inputfile":
        mid.save(args.inputfile.split('.')[0] + ".mid")
    else:
        mid.save(args.outputfile)

    if args.play:
        port = mido.open_output()
        for msg in mid.play():
            port.send(msg)
            #print(rectArray[:,:NUM_TRACKS * chunk + NUM_TRACKS])

            chunk += 1

    return rectArray


def playMidi(mid):

    for message in mid.play():
        #print(message)
        outport.send(message)


outport = mido.open_output()

noteArray = np.random.randint(0, 128, size=(NUM_TRACKS, SONG_LENGTH))
velocityArray = np.random.randint(0, 128, size=(NUM_TRACKS, SONG_LENGTH))
onOffArray = np.random.randint(-1, 2, size=(NUM_TRACKS, SONG_LENGTH))

noteArray_square = toSquareArray(noteArray)

#midiFunctions.createMidi(noteArray, velocityArray, onOffArray, int(round(60000000 / TEMPO)), "new_song")

noteArray_sources = []
velocityArray_sources = []
onOffArray_sources = []

for i in range(len(FILESOURCES)):
    noteArray_source, velocityArray_source, onOffArray_source = midiFunctions.parseMidi(