在python中播放MIDI文件?

YeJ*_*bin 17 python midi

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

Vij*_*jay 15

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


duh*_*ime 7

只是添加一个最小的例子(通过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
Run Code Online (Sandbox Code Playgroud)


Kal*_*zvx 5

Pretty_midi可以为您生成波形,然后您可以使用 egIPython.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)
Run Code Online (Sandbox Code Playgroud)

  • 似乎是比远程相关的 pygame 更好(更轻)的解决方案。[两位知名作者的展示案例](https://www.audiolabs-erlangen.de/resources/MIR/FMP/C1/C1S2_MIDI.html) 音乐分析和 DSP。 (3认同)