我正在寻找一种在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
只是添加一个最小的例子(通过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)
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)