在python中播放MIDI文件?

时间:2011-05-17 11:26:52

标签: python midi

我正在寻找一种在python中播放midi文件的方法。 似乎python在其标准库中不支持MIDI。 在我搜索之后,我找到了一些python midi图书馆,例如pythonmidi。 但是,大多数只能创建和读取MIDI文件而无需播放功能。 我想找一个包含播放方法的python midi库。 有什么建议?谢谢!

4 个答案:

答案 0 :(得分:14)

pygame模块可用于播放midi文件。

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

请参阅此处的示例:

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

提供了大量选项:

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

以及您可以在此修改以满足您的目的: http://xenon.stanford.edu/~geksiong/code/playmus/playmus.py

答案 1 :(得分:4)

使用pygame播放您的midi文件。示例包括herehere

答案 2 :(得分:4)

pretty_midi 可以为您生成波形,然后您可以使用例如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)

答案 3 :(得分:2)

只需添加一个最小示例(通过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