Skip to content

Instantly share code, notes, and snippets.

@f-rumblefish
Last active January 7, 2023 01:50
Show Gist options
  • Save f-rumblefish/4b8bff2791a7ee61c8087b75f30a3a23 to your computer and use it in GitHub Desktop.
Save f-rumblefish/4b8bff2791a7ee61c8087b75f30a3a23 to your computer and use it in GitHub Desktop.
Using pygame to play notes
# import library ---------------------------------------------------------------
import pygame.midi
import time
# define all the constant values -----------------------------------------------
device = 0 # device number in win10 laptop
instrument = 9 # http://www.ccarh.org/courses/253/handout/gminstruments/
note_Do = 48 # http://www.electronics.dit.ie/staff/tscarff/Music_technology/midi/midi_note_numbers_for_octaves.htm
note_Re = 50
note_Me = 52
volume = 127
wait_time = 0.5
# initize Pygame MIDI ----------------------------------------------------------
pygame.midi.init()
# set the output device --------------------------------------------------------
player = pygame.midi.Output(device)
# set the instrument -----------------------------------------------------------
player.set_instrument(instrument)
# play the notes ---------------------------------------------------------------
player.note_on(note_Do, volume)
time.sleep(wait_time)
player.note_off(note_Do, volume)
player.note_on(note_Re, volume)
time.sleep(wait_time)
player.note_off(note_Re, volume)
player.note_on(note_Me, volume)
time.sleep(wait_time)
player.note_off(note_Me, volume)
# close the device -------------------------------------------------------------
del player
pygame.midi.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment