在Python中播放MIDI文件?

31 投票
6 回答
40104 浏览
提问于 2025-04-16 17:48

我想找一种方法在Python中播放MIDI文件。 看起来Python的标准库并不支持MIDI。 我搜索了一下,发现了一些Python的MIDI库,比如pythonmidi。 不过,大多数库只能创建和读取MIDI文件,而没有播放的功能。 我希望能找到一个包含播放功能的Python MIDI库。 有什么推荐的吗?谢谢!

6 个回答

8

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)
10

这里给大家补充一个简单的例子(来自 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
18

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

撰写回答