Last active
May 23, 2020 17:11
Star
You must be signed in to star a gist
play midi file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# conda install -c cogsci pygame | |
import pygame, base64 | |
def midi_to_base64(midi_filename): | |
return base64.encodestring(open(midi_filename, 'rb').read()) | |
def play_music(midi_filename): | |
'''Stream music_file in a blocking manner''' | |
clock = pygame.time.Clock() | |
pygame.mixer.music.load(midi_filename) | |
pygame.mixer.music.play() | |
while pygame.mixer.music.get_busy(): | |
clock.tick(30) # check if playback has finished | |
midi_filename = 'FishPolka.mid' | |
# mixer config | |
freq = 44100 # audio CD quality | |
bitsize = -16 # unsigned 16 bit | |
channels = 2 # 1 is mono, 2 is stereo | |
buffer = 1024 # number of samples | |
pygame.mixer.init(freq, bitsize, channels, buffer) | |
# optional volume 0 to 1.0 | |
pygame.mixer.music.set_volume(0.8) | |
# listen for interruptions | |
try: | |
# use the midi file you just saved | |
play_music(midi_filename) | |
except KeyboardInterrupt: | |
# if user hits Ctrl/C then exit | |
# (works only in console mode) | |
pygame.mixer.music.fadeout(1000) | |
pygame.mixer.music.stop() | |
raise SystemExit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment