示例#1
0
    def __init__(self, difficulty):
        super(AudioController, self).__init__()

        self.MIDI_ENABLED = True

        self.audio = Audio(2)
        self.synth = Synth("data/FluidR3_GM.sf2")

        self.mixer = Mixer()
        self.audio.set_generator(self.mixer)
        self.mixer.add(self.synth)

        self.channel = 1
        self.synth.program(self.channel, 0, 0)

        self.song = 'hallelujah'

        if difficulty == "easy":
            self.bg_wave_file_gen = WaveGenerator(WaveFile("data/hallelujah_harp_delay.wav"))
        elif difficulty == "medium":
            self.bg_wave_file_gen = WaveGenerator(WaveFile("data/falling_delay.wav"))
        elif difficulty == "hard": #difficulty == "hard"
            self.bg_wave_file_gen = WaveGenerator(WaveFile("data/hallelujah_harp_delay.wav"))

        self.bg_wave_file_gen.set_gain(0.5)
        self.mixer.add(self.bg_wave_file_gen)

        if(self.MIDI_ENABLED is True):
            self.midi_in = rtmidi.MidiIn(b'in')
            self.midi_in.open_port(0)
示例#2
0
    def __init__(self):
        
        QObject.__init__(self)

        print 'Open MIDI input device.'
        self.device = rtmidi.MidiIn()
        self.device.callback = self.deviceCallback
示例#3
0
文件: midi.py 项目: hiway/tacpyle
def start_listening(callback_method, port=0, sleep_time=0.2):
    midi_in = rtmidi.MidiIn()
    midi_in.callback = callback_method
    midi_in.open_port(port)

    while True:
        sleep(sleep_time)
        
示例#4
0
    def __init__(self, machine_type):
        super(FapoGame, self).__init__(machine_type)
        self.gameConfig = GameConfig.GameConfig()
        self.ball_start_time = 0
        self.midiMap = None
        self.midiLampMap = None
        if self.gameConfig.inputKeyboardTest:
            self.midiMap = self.gameConfig.midiKeyboardMap
        self.midiLampMap = None
        if self.gameConfig.inputLaunchpadTest:
            self.midiLampMap = self.gameConfig.midiLaunchpadMap

        self.load_config('config/funhouse.yaml')

        ### ALPHANUMERIC DISPLAY ###
        self.aux_port = auxport2.AuxPort(self)
        self.alpha_display = alphanumeric2.AlphanumericDisplay(self.aux_port)
        # self.scoredisplay = scoredisplay.AlphaScoreDisplay(self,4) # blink text

        ### MODES ###
        self.basic_mode = BasicMode.BasicMode(game=self)
        self.idle_mode = IdleMode.IdleMode(game=self)
        self.steps_mode = StepsMode.StepsMode(game=self)
        self.alpha_mode = scoredisplay.AlphaScoreDisplay(game=self, priority=5)
        self.trough_mode = procgame.modes.trough.Trough(
            self, ["trough1", "trough2", "trough3"], "trough1", "trough", [],
            "shooterR", self.ballDrained)

        ### MIDI HANDLING ###
        self.midi_in_sol = rtmidi.MidiIn()
        self.midi_in_sol.open_port(self.gameConfig.inputMidiSolenoids)
        self.midi_in_lamp = rtmidi.MidiIn()
        self.midi_in_lamp.open_port(self.gameConfig.inputMidiLamps)
        self.midi_out = rtmidi.MidiOut()
        self.midi_out.open_port(self.gameConfig.outputMidiSwitches)
        self.addSwitchHandlers()

        ### LAMP SHOWS ###
        self.lampctrl = procgame.lamps.LampController(self)
        self.lampctrl.register_show('attract', 'lamps/attract.lampshow')
        self.lampctrl.register_show('start', 'lamps/start.lampshow')
        self.lampctrl.register_show('trapdoorOpen',
                                    'lamps/trapdoorOpen.lampshow')

        print self.lamps
示例#5
0
    def __init__(self, port=0, cc_callback, sysex_callback):
        """Set up midi interface"""
        self.midi_out = rtmidi.MidiOut()
        self.midi_out.open_port(port)

        self.midi_in = rtmidi.MidiIn()
        self.midi_in.callback = self._on_midi
        self.midi_in.open_port(port)

        self.cc_callback = cc_callback
        self.sysex_callback = sysex_callback
        def midi_read(socket_io, stop):
            midi_in = rtmidi_python.MidiIn(b'in')
            if self._debug:
                for port in midi_in.ports:
                    print("In Port: %s" % port)

            midi_in.open_port(self._config['midi_port_in'])

            knob_temp_values = {}

            while not self._stop_midi_in.is_set():
                now = time.time()
                keys_to_delete = []
                for knob_key, knob_value in knob_temp_values.items():
                    if now - knob_value['time'] >= self._config['knob_accept_time_ms'] / 1000:
                        # Fire the knob change event
                        new_value = self.compute_knob_value(knob_key, knob_value['value'])
                        device_id, value_change = self._set_value_by_key(
                            key='midi_port',
                            value=knob_key,
                            new_value=new_value,
                            update_types=[Update.PIMATIC]
                        )

                        # We cannot delete the key while iterating, so we do this after the iteration
                        keys_to_delete.append(knob_key)
                for key in keys_to_delete:
                    del knob_temp_values[key]

                message, delta_time = midi_in.get_message()
                if message:
                    if message[0] == self._config['midi_pad_on']:
                        pass
                    elif message[0] == self._config['midi_pad_off']:
                        # A pad button was released
                        device_id, value_change = self._set_value_by_key(
                            key='midi_port',
                            value=message[1],
                            update_types=[Update.PIMATIC, Update.MIDI]
                        )
                    elif message[0] == self._config['knob_type']:
                        # A knob was changed
                        # print("Knob was changed: %s" % message)
                        knob_temp_values[message[1]] = {
                            'value': message[2],
                            'time': time.time()
                        }

                    elif self._debug:
                        print("Unrecognized midi input: %s" % message)

                time.sleep(0.01)
 def get_info(self):
     d = {'in': rtmidi.MidiIn(), 'out': rtmidi.MidiOut()}
     i = 0
     for key, dev in d.iteritems():
         for devindex, name in enumerate(dev.ports):
             devinfo = {
                 'type': key,
                 'name': name,
                 'id': 'in:%d' % (devindex),
                 'Index': i
             }
             yield devinfo
             i += 1
示例#8
0
def get_devices(api=None, **kwargs):
    devices = []

    input_names = set(rtmidi.MidiIn().ports)
    output_names = set(rtmidi.MidiOut().ports)

    for name in sorted(input_names | output_names):
        devices.append({
            'name': name,
            'is_input': name in input_names,
            'is_output': name in output_names,
        })

    return devices
示例#9
0
def get_devices(api=None, **kwargs):
    devices = []

    input_names = rtmidi.MidiIn().ports
    output_names = rtmidi.MidiOut().ports

    for name in input_names + output_names:
        devices.append({
            'name': name,
            'is_input': name in input_names,
            'is_output': name in output_names,
        })

    return devices
示例#10
0
def get_devices(api=None, **kwargs):
    devices = {}

    input_names = rtmidi.MidiIn().ports
    output_names = rtmidi.MidiOut().ports

    for name in input_names + output_names:
        if name not in devices:
            devices[name] = {
                'name': name,
                'is_input': name in input_names,
                'is_output': name in output_names,
            }

    return list(devices.values())
示例#11
0
    def _open(self, virtual=False, **kwargs):

        self._queue = queue.Queue()
        self._callback = None

        # rtapi = _get_api_id(api)
        opening_input = hasattr(self, 'receive')

        if opening_input:
            self._rt = rtmidi.MidiIn()
            self._rt.ignore_types(False, False, True)
            self.callback = kwargs.get('callback')
        else:
            self._rt = rtmidi.MidiOut()  # rtapi=rtapi)
            # Turn of ignore of sysex, time and active_sensing.

        ports = self._rt.ports

        if virtual:
            if self.name is None:
                raise IOError('virtual port must have a name')
            self._rt.open_virtual_port(self.name)
        else:
            if self.name is None:
                # TODO: this could fail if list is empty.
                # In RtMidi, the default port is the first port.
                try:
                    self.name = ports[0]
                except IndexError:
                    raise IOError('no ports available')

            try:
                port_id = ports.index(self.name)
            except ValueError:
                raise IOError('unknown port {!r}'.format(self.name))

            try:
                self._rt.open_port(port_id)
            except RuntimeError as err:
                raise IOError(*err.args)

        # api = _api_to_name[self._rt.get_current_api()]
        api = ''
        self._device_type = 'RtMidi/{}'.format(api)
        if virtual:
            self._device_type = 'virtual {}'.format(self._device_type)
示例#12
0
文件: rtm.py 项目: kieroneil/mido
    def _open(self, virtual=False, callback=None):
        opening_input = hasattr(self, 'receive')

        if opening_input:
            self._rt = rtmidi.MidiIn()
            self._rt.ignore_types(False, False, False)
            if callback:

                def callback_wrapper(message, delta_time):
                    self._parser.feed(message)
                    for message in self._parser:
                        callback(message)

                self._rt.callback = self._callback = callback_wrapper
                self._has_callback = True
            else:
                self._has_callback = False
        else:
            self._rt = rtmidi.MidiOut()
            # Turn of ignore of sysex, time and active_sensing.

        ports = self._rt.ports

        if virtual:
            if self.name is None:
                raise IOError('virtual port must have a name')
            self._rt.open_virtual_port(self.name)
        else:
            if self.name is None:
                # Todo: this could fail if list is empty.
                # In RtMidi, the default port is the first port.
                try:
                    self.name = ports[0]
                except IndexError:
                    raise IOError('no ports available')

            try:
                port_id = ports.index(self.name)
            except ValueError:
                raise IOError('unknown port {!r}'.format(self.name))

            self._rt.open_port(port_id)

        self._device_type = 'rtmidi_python'
def main( ):
    handshake_message = "{0};{1};{2}".format(
        USERNAME,CLIENT_TYPE,
        'handshake'
        )

    MIDI_TO_SERVER_SOCKET.sendto( 
        handshake_message.encode('utf-8'), 
        SERVER_ENDPOINT
        )

    midi_in = rtmidi.MidiIn(''.encode('utf-8'))

    midi_in.callback = callback

    midi_in.open_port(0)

    # do something else here (but don't quit)
    while True: 
        time.sleep( 0.001 )
示例#14
0
def startMidi():
    import rtmidi_python as rtmidi
    midi_in = rtmidi.MidiIn()
    available_ports_in = midi_in.ports
    print(available_ports_in)

    midi_in.open_port(1)
    image = Image.new('1', (128, 64))
    draw = ImageDraw.Draw(image)
    displayImage(image)

    import serial
    ser = serial.Serial('/dev/ttyAMA0', baudrate=38400)
    while True:
        message, delta_time = midi_in.get_message()
        if message and message != [248]:
            print(message)

            # for i in message:
            #     print(hex(i))
            print(toHex(message[0])+" "+str(message[1])+" "+str(message[2]))
            ser.write(toHex(message[0])+" "+str(message[1])+" "+str(message[2]))
示例#15
0
def connect_midi(cli_port, settings_port):
    port = None
    midiout = rtmidi_python.MidiOut()
    midiin = rtmidi_python.MidiIn()
    midiin.ignore_types(midi_sysex=False)

    if cli_port is None:
        port = settings_port or None
    else:
        port = cli_port

    if port is None:
        raise click.UsageError(
            "No port specified ({} currently connected)".format(", ".join(
                midiin.ports)))
    try:
        midiin.open_port(port)
        midiout.open_port(port)
    except ValueError:
        raise click.UsageError(
            "Unable to connect to {}. Is the device connected?".format(port))

    return midiin, midiout, port
示例#16
0
        def __init__(self, bpm=120, time_sig=4, real_hardware=False):
                self.bpm = bpm
		self.real_hardware = real_hardware
                self.bps = bpm/60.0
                self._valid_time_sigs = [2, 3, 4]
                if time_sig not in self._valid_time_sigs:
                        print("uh oh time sig not valid")
                        raise
                self.time_sig = time_sig
                self.current_time = time.time()
                self.bar_length_seconds = self.bps * time_sig
                self.last_remainder = 0
		self.data = MidiData("test")
                self.beat_time_s = self.bar_length_seconds / 20
		self.timer2 = time.time()
                self.buffer = {(self.beat_time_s*x):None for x in range(0, 100)}
		if self.real_hardware:
			self.midi_in = rtmidi.MidiIn()
			self.midi_in.callback = self.callback
			self.midi_in.open_port(0)
			self.midi_out = rtmidi.MidiOut()
			self.midi_out.open_port(0)
		self.samples = []
		self.beat_dict = {j:None for j in range(0, 16)}
示例#17
0
#########################################
# MIDI DEVICES DETECTION
# MAIN LOOP
#########################################


def handle_args():
    from argparse import ArgumentParser
    global preset
    parser = ArgumentParser()
    parser.add_argument("-p", "--preset", type=int, default=0)
    args = parser.parse_args()
    preset = args.preset


if __name__ == "__main__":
    handle_args()
    LoadSamples()

    midi_in = [rtmidi.MidiIn(b"in")]
    previous = []
    while True:
        for port in midi_in[0].ports:
            if port not in previous and b"Midi Through" not in port:
                midi_in.append(rtmidi.MidiIn(b"in"))
                midi_in[-1].callback = MidiCallback
                midi_in[-1].open_port(port)
                print(b"Opened MIDI: " + port)
        previous = midi_in[0].ports
        time.sleep(2)
示例#18
0
BLINKING_RATE_READY = 1.5
BLINKING_RATE_WAITING = 0.1
BLINKING_RATE_LOADING = 0.3
PIN_BUTTON = 3
PIN_BLUE = 23
PIN_RED = 24

import os, sys, time, signal, subprocess, json
import rtmidi_python as rtmidi
import RPi.GPIO as GPIO

midi_in = [rtmidi.MidiIn()]
attached = set()
attached.add(midi_in[0].ports[0])
p = None

with open('noise-control.json') as map_file:
    map = json.load(map_file)


def button_callback(channel):
    kill_cmd(None)
    GPIO.cleanup()
    log('shutdown now!')
    os.system("shutdown now -h")


GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_RED, GPIO.OUT)
GPIO.setup(PIN_BLUE, GPIO.OUT)
示例#19
0
    MidiThread = threading.Thread(target=MidiSerialCallback)
    MidiThread.daemon = True
    MidiThread.start()


#########################################
# LOAD FIRST SOUNDBANK
#
#########################################

preset = 0
LoadSamples()


#########################################
# MIDI DEVICES DETECTION
# MAIN LOOP
#########################################

midi_in = [rtmidi.MidiIn()]
previous = []
while True:
    for port in midi_in[0].ports:
        if port not in previous and 'Midi Through' not in port:
            midi_in.append(rtmidi.MidiIn())
            midi_in[-1].callback = MidiCallback
            midi_in[-1].open_port(port)
            print 'Opened MIDI: ' + port
    previous = midi_in[0].ports
    time.sleep(2)
示例#20
0
def playNotes(arr):
    for note in arr:
        clientmusic.send_message("/mididata", [note, 110])
        time.sleep(.5)
    print("Shimon played notes:", arr)


'''
Method that makes shimon do the gesture indicating correct notes by the player
'''


def correctGesture():
    clientGest.send_message("0", "good")
    print("shimon does good gesture")


'''
Method that makes shimon do the gesture indicating incorrect notes by the player
'''


def wrongGesture():
    clientGest.send_message("1", "bad")
    print("shimon does bad gesture")


midi_in = rtmidi.MidiIn(b"input")
midi_in.open_port(0)
start()
示例#21
0
    def setUp(self):
        self.midi_out = rtmidi.MidiOut()
        self.midi_out.open_virtual_port(self.TEST_PORT_NAME)

        self.midi_in = rtmidi.MidiIn()
        self.midi_in.open_port(self.TEST_PORT_NAME)
import rtmidi_python as rtmidi
import os
midi_virtual = rtmidi.MidiIn()
midi_virtual.open_virtual_port("Midi")
print "Loading Midi Virtual port..."
os.system("aplaymidi -l")
示例#23
0
            MidiCallback(message, None)

    MidiThread = threading.Thread(target=MidiSerialCallback)
    MidiThread.daemon = True
    MidiThread.start()

#########################################
# LOAD FIRST SOUNDBANK
#
#########################################

preset = 0
LoadSamples()

#########################################
# MIDI DEVICES DETECTION
# MAIN LOOP
#########################################

midi_in = [rtmidi.MidiIn(b'in')]
previous = []
while True:
    for port in midi_in[0].ports:
        if port not in previous and b'Midi Through' not in port:
            midi_in.append(rtmidi.MidiIn(b'in'))
            midi_in[-1].callback = MidiCallback
            midi_in[-1].open_port(port)
            print('Opened MIDI: ' + str(port))
    previous = midi_in[0].ports
    time.sleep(2)
示例#24
0
                break
            i = i + 1
        if message[2] > 0:
            libpd_float(("note" + str(i + 1)), 1)
    elif message[0] == 128:
        if message[1] in osc:
            i = osc.index(message[1])
            libpd_float(("note" + str(i + 1)), 0)
            osc[i] = 0


def midi_callback_theremin(message, time_stamp):
    if message[1] == 20:
        libpd_float("midi", message[2] + 12)
    elif message[1] == 2 and message[2] > 0:
        libpd_float("note", 1)
    elif message[1] == 2 and message[2] == 0:
        libpd_float("note", 0)


midi_in = rtmidi.MidiIn()
#print ('hey', STATION_NUMBER)
if STATION_NUMBER == 'Piano' or STATION_NUMBER == 'Push':
    midi_in.callback = midi_callback_poly
elif STATION_NUMBER == 'Theremin':
    #print 'hi'
    midi_in.callback = midi_callback_theremin
midi_in.open_port(1)

while ALIVE == True:
    time.sleep(2)
import rtmidi_python as rtmidi
from comserie import Serie
import serial
midi_in = rtmidi.MidiIn(b'')
midi_in.open_port(1)

s = Serie(57600)
portSerie = ""
for key in s.ports:
    portSerie = s.ports.get(key)

print(s.ports)
print("Connection à la carte %s" % portSerie)
arduino = serial.Serial(portSerie, 57600)
print("Connected")

while True:
    message, delta_time = midi_in.get_message()
    if message:
        r = message[0] << 16 | message[1] << 8 | message[2]
        print(message[1])
        arduino.write(bytearray([message[0], message[1], message[2]]))
 def build_device(self, **kwargs):
     return rtmidi.MidiIn()
示例#27
0
def initmidiinout():
    global midiout, midiin
    midiout = rtmidi.MidiOut(b'out')
    midiin = rtmidi.MidiIn(b'in')