Playing note with pygame.midi

cym13 picture cym13 · Apr 7, 2013 · Viewed 15.9k times · Source

I'm trying to play a sound with the pygame.midi module. Here is the code I use :

#!/usr/bin/env python

import pygame.midi
import time

pygame.midi.init()

print pygame.midi.get_default_output_id()
print pygame.midi.get_device_info(0)

player = pygame.midi.Output(0)

player.set_instrument(0)

print 'Playing...'

player.note_on(64)
time.sleep(1)
player.note_off(64)

print 'Played'

pygame.midi.quit()

I've found similar codes while searching for exemples, here is the output :

0

('ALSA', 'Midi Through Port-0', 0, 1, 0)

Playing...

Played

PortMidi call failed...

PortMidi: `Bad pointer'

type ENTER...

No sound is played, and I didn't find any info about the PortMidi error which occurs surprisingly after pygame.midi quits.

Do you have any idea? I'm running an debian-based linux distribution if that can help.

Answer

Cito picture Cito · Jul 31, 2014

There are two small problems. The sound is not played because you don't set the velocity of the note. Try setting it to 127 (maximum) to hear the sound. The other problem is that you don't delete the midi output object at the end before quitting. This leads to the "PortMidi: `Bad pointer'" error at the end. So here is the corrected code that should work properly:

import pygame.midi
import time

pygame.midi.init()
player = pygame.midi.Output(0)
player.set_instrument(0)
player.note_on(64, 127)
time.sleep(1)
player.note_off(64, 127)
del player
pygame.midi.quit()