Notating Computer Keyboard Input

Example script (scamp): examples/Notation & engraving/From live input/keyboard_input_with_notation.py

Download: keyboard_input_with_notation.py

(WARNING: consumes key events and makes the keyboard otherwise unresponsive. To avoid this, you can remove the suppress=True flag under register_keyboard_listener) Same as Computer Keyboard Input, except that a metronome is playing back while the user plays notes with the keyboard, and the result is rendered as music notation.

Topics: Notation & engraving › From live input, Interactivity & visualization › Keyboard input

from scamp import *

s = Session()

piano = s.new_part("piano")
perc = s.new_part("power")
s.start_transcribing(piano)

# dictionary mapping keys that are down to the NoteHandles used to manipulate them.
notes_started = {}


def key_down(name, number):
    if number == 27:
        s.kill()
        return

    if 20 < number < 110 and number not in notes_started:
        notes_started[number] = piano.start_note(number, 0.5)


def key_up(name, number):
    if 20 < number < 110 and number in notes_started:
        notes_started[number].end()
        del notes_started[number]


def metro():
    while True:
        perc.play_note(60, 1, 1)


fork(metro)

# note: suppress=True causes keyboard events to be consumed by this script, effectively disabling the keyboard
s.register_keyboard_listener(on_press=key_down, on_release=key_up, suppress=True)

with s:
    # the context manager captures clock (session) kill gracefully, but we also need to
    # catch a KeyboardInterrupt if we want to build the score on ctrl-C
    try:
        wait_forever()
    except KeyboardInterrupt:
        pass

s.stop_transcribing().to_score().show()