Search code examples
pythonpygamemidi

Python Pygame.midi get note octave


Have a code that reads what note pressed on the midi:

import pygame.midi

def number_to_note(number):
    notes = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b']
    return notes[number%12]

def readInput(input_device):
    while True:
        if input_device.poll():
            event = input_device.read(1)[0]
            data = event[0]
            timestamp = event[1]
            note_number = data[1]
            velocity = data[2]
            print(number_to_note(note_number))
            note = number_to_note(note_number)

if __name__ == '__main__':
    pygame.midi.init()
    my_input = pygame.midi.Input(1)
    readInput(my_input)

It says the note, but how do I get in what octave the note is? For example: Not just A#, but A4#


Solution

  • You just need to do some arithmetic with your note:

    note = number%12
    octave = (number - note) / 12
    return str(octave) + notes[note]