play MIDI files in python?

Question:

I’m looking for a method to play midi files in python.
It seems python does not support MIDI in its standard library.
After I searched, I found some python midi librarys such as pythonmidi.
However, most of them can only create and read MIDI file without playing function.
I would like to find a python midi library including playing method.
Any recommendations? Thanks!

Asked By: YeJiabin

||

Answers:

Use pygame to play your midi file. Examples are here or here

Answered By: Ocaso Protal

The pygame module can be used to play midi files.

http://www.pygame.org/docs/ref/music.html

See the example here:

http://www.daniweb.com/software-development/python/code/216979

a whole bunch of options available at:

http://wiki.python.org/moin/PythonInMusic

and also here which you can modify to suit your purpose:
http://xenon.stanford.edu/~geksiong/code/playmus/playmus.py

Answered By: Vijay

Just to add a minimal example (via DaniWeb):

# conda install -c cogsci pygame
import pygame

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
Answered By: duhaime

pretty_midi can generate the waveform for you, you can then play it with e.g. IPython.display.Audio

from IPython.display import Audio
from pretty_midi import PrettyMIDI

sf2_path = 'path/to/sf2'  # path to sound font file
midi_file = 'music.mid'

music = PrettyMIDI(midi_file=midi_file)
waveform = music.fluidsynth(sf2_path=sf2_path)
Audio(waveform, rate=44100)
Answered By: Kallzvx

I find that midi2audio works well.

Example:

from midi2audio import FluidSynth

#Play MIDI

FluidSynth().play_midi('input.mid')

#Synthesize MIDI to audio

# Note: the default sound font is in 44100 Hz sample rate

fs = FluidSynth()
fs.midi_to_audio('input.mid', 'output.wav')

# FLAC, a lossless codec, is recommended

fs.midi_to_audio('input.mid', 'output.flac')
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.