本文整理汇总了Python中mido.open_input函数的典型用法代码示例。如果您正苦于以下问题:Python open_input函数的具体用法?Python open_input怎么用?Python open_input使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了open_input函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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()
示例2: eloop
def eloop(self, render_callback):
cb = callback_factory(render_callback)
try:
midin = mido.open_input(
name=self.port, virtual=True, callback=cb)
except IOError: # couldn't create virtual port
midin = mido.open_input(name=self.port, callback=cb)
except:
raise complain.ComplainToUser("Could not find a valid MIDI input")
midin.close()
示例3: __init__
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)
示例4: messages
def messages(self):
if not mido:
raise ValueError(MIDO_ERROR)
try:
input_names = mido.get_input_names()
except AttributeError as e:
e.args = (MIDO_ERROR,) + e.args
raise
ports = [mido.open_input(i) for i in input_names]
if not ports:
log.error('control.midi: no MIDI ports found')
return
port_names = ', '.join('"%s"' % p.name for p in ports)
log.info('Starting to listen for MIDI on port%s %s',
'' if len(ports) == 1 else 's', port_names)
for port, msg in mido.ports.MultiPort(ports, yield_ports=True):
mdict = dict(vars(msg), port=port)
if self.use_note_off:
if msg.type == 'note_on' and not msg.velocity:
mdict.update(type='note_off')
elif self.use_note_off is False:
if msg.type == 'note_off':
mdict.update(type='note_on', velocity=0)
yield mdict
示例5: start_key_thread
def start_key_thread(self):
port_name = mido.get_input_names()[0]
with mido.open_input(port_name) as inport:
for msg in inport:
if self.done: return
if not self.current_note_to_play:
print("cannot play notes during this state!")
continue
if hasattr(msg, 'note') and hasattr(msg, 'velocity') and msg.velocity > 0:
print(msg.note)
self.total_notes += 1
self.display_total_notes = self.info_font.render("Total Notes: " + str(self.total_notes), True,
(205, 92, 92))
if hasattr(msg, 'note') and msg.note % 12 == self.current_note_to_play % 12 and hasattr(msg,
'velocity') and msg.velocity > 0:
self.notes_correct += 1
self.display_note = self.note_font.render("Correct!!!", True, (0, 128, 0))
self.display_notes_correct = self.info_font.render("Correct Notes: " + str(self.notes_correct),
True, (205, 92, 92))
self.display_average_tries = self.info_font.render(
"Average Tries: " + str(round(self.total_notes / self.notes_correct)), True, (205, 92, 92))
self.average_note_time += time.time() - self.note_start_time
self.display_average_time = self.info_font.render(
"Average Time: " + str(round(self.average_note_time / self.notes_correct, 1)) + " seconds",
True,
(205, 92, 92))
self.current_note_to_play = 0
Thread(target=self.new_note()).start()
示例6: __init__
def __init__(self, port_name, trace=False):
"""
Construct new MIDIReceiver object.
DO NOT instinate directly, use get_midi_receiver function instead.
ARGS:
port_name - String.
For a list of available ports execute the mido-ports
script on the command line.
"""
self._dispatch_table = {"note_on" : {},
"note_off" : {},
"program_change" : {},
"aftertouch" : {},
"control_change" : {},
"pitchwheel" : {},
"polytouch" : {},
"sysex" : {},
"quarter_frame" : {},
"songpos" : {},
"song_select" : {},
"tune_request" : {},
"clock" : {},
"start" : {},
"continue" : {},
"stop" : {},
"reset" : {},
"active_sensing" : {}}
self._port_name = port_name
self._port = mido.open_input(self._port_name)
self._thread = None
self._active = False
self.enable_trace(trace)
示例7: play_from_encoder
def play_from_encoder(directory):
encoder = pickle_loader(directory + ".pkl")
sample_rate = encoder.sample_rate
buffer_size = 10 # sample buffer for playback. Hevent really determined what i does qualitatively. Probably affects latency
play_duration = 100 # play duration in miliseconds
pygame.mixer.pre_init(sample_rate, -16, 2,buffer = buffer_size) # 44.1kHz, 16-bit signed, stereo
pygame.init()
volLeft = 0.5;volRight=0.5 # Volume
z_val = np.zeros([1,encoder.dimZ]) # Initial latent variable values
port = mido.open_input(mido.get_input_names()[0]) # midi port. chooses the first midi device it detects.
while True:
mu_out = encoder.generateOutput(z_val)
for msg in port.iter_pending():
if msg.channel < z_val.shape[1]:
z_val[0,msg.channel] = msg.value
else:
print "Midi channel beyond latent variables"
mu_out = map_to_range_symmetric(mu_out,[-1,1],[-32768,32768])
mu_out = mu_out.astype(np.int16)
mu_out = np.array(zip(mu_out,mu_out)) # make stereo channel with same output
sound = pygame.sndarray.make_sound(mu_out)
channel = sound.play(-1)
channel.set_volume(volLeft,volRight)
pygame.time.delay(play_duration)
sound.stop()
示例8: capture
def capture(self):
self.capturing = False
self.final_tick = False
# Start clocks at -1 to account for Circuit's leading clock message after start
self.clocks = [-1, -1, -1]
self.total_ticks = 0
output_dir = os.path.dirname(self.output)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
mido.set_backend('mido.backends.rtmidi')
with mido.MidiFile(type=1, ticks_per_beat=TICKS_PER_BEAT) as mid:
# Create tracks
self.tempo_map_track = mid.add_track(name=SONG_NAME)
self.tracks = [mid.add_track(name="Synth 1"),
mid.add_track(name="Synth 2"),
mid.add_track(name="Drums")]
# Set synth instruments
self.tracks[CHANNEL_SYNTH1].append(mido.Message('program_change', program=PROGRAM_SYNTH1))
self.tracks[CHANNEL_SYNTH2].append(mido.Message('program_change', program=PROGRAM_SYNTH2))
with mido.open_input(self.input) as port:
print("Push 'Play' to start capture.")
for msg in port:
if not self.process_message(msg):
break
self.capturing = False
self.write_tempo_map()
mid.save(self.output)
print("All done!")
示例9: main
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"
示例10: start_midi_stream
def start_midi_stream(file_name, display):
last_note = int(round(time.time() * 1000))
mido.get_output_names()
port_name = mido.get_input_names()[0]
print('Starting on port: ' + port_name)
with MidiFile() as mid:
track = MidiTrack()
try:
print("Waiting For Keyboard Input ... ")
with mido.open_input(port_name) as inport:
for msg in inport:
now = int(round(time.time() * 1000))
msg.time = now - last_note
last_note = now
if hasattr(msg, 'velocity') and msg.velocity == 0:
msg = Message('note_off', note=msg.note, velocity=msg.velocity, time=msg.time)
track.append(msg)
if display:
print(msg)
except KeyboardInterrupt:
if file_name:
print("\nStopping and saving file ... ")
else:
print("\nStopping ...")
finally:
if file_name:
print(file_name)
mid.tracks.append(track)
mid.save(file_name)
print("File Saved!")
print("File Location: " + file_name)
else:
print("Done!")
示例11: __init__
def __init__(self):
self.log = logger()
if 'Teensy MIDI' not in mido.get_input_names():
self.log.error('Error connecting to Teensy foot controller.')
sys.exit(1)
self.input = mido.open_input(MidiController.DEVICE)
self.log.info('Device Registered.')
示例12: open_port
def open_port(self, portName):
if not self.port or self.port.name != portName:
if self.port:
self.port.close()
print(portName)
if portName in mido.get_input_names():
self.port = mido.open_input(portName, callback=self.dispatch_midi)
示例13: __init__
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
示例14: start
def start(self):
if self.midi_inport:
with mido.open_input(self.midi_inport) as input:
for message in input:
if message.type == 'control_change':
if message.channel == self.channel:
if message.control == self.bcontrolnum:
self.beat.set_control_beat(message.value)
elif message.control == self.tcontrolnum:
self.bpm.set_control_bpm(message.value)
elif message.control == self.rcontrolnum:
self.rms.set_control_rms(message.value)
elif message.control == self.pcontrolnum:
self.pitch.set_control_pitch(message.value)
elif message.type == 'sysex':
prefix = list(message.data[0:len(self.sysex_prefix)])
command = message.data[len(self.sysex_prefix)]
data = list(message.data[len(self.sysex_prefix) + 1:])
if cmp(prefix, self.sysex_prefix) == 0:
if command == self.bsysexnum:
self.beat.set_sysex_beat(data)
elif command == self.tsysexnum:
self.bpm.set_sysex_bpm_two_bytes(data)
elif command == self.rsysexnum:
self.rms.set_sysex_rms(data)
elif command == self.fsysexnum:
self.frequencies.set_sysex_frequencies(data)
elif command == self.psysexnum:
self.pitch.set_sysex_pitch(data)
elif message.channel == self.channel:
if message.type == 'note_on':
self.pitch.set_note_pitch(message.note)
elif message.type == 'note_off':
self.pitch.set_last_note_pitch(message.note)
示例15: wait
def wait(self):
with mido.open_input(self.device_name) as incoming:
for msg in incoming:
if msg.type == 'note_on' and msg.note in self.notes:
return (msg.note, msg.velocity)
return False