简体   繁体   English

在 python 中播放 MIDI 文件?

[英]play MIDI files in python?

I'm looking for a method to play midi files in python.我正在寻找一种在 python 中播放 MIDI 文件的方法。 It seems python does not support MIDI in its standard library.似乎 python 在其标准库中不支持 MIDI。 After I searched, I found some python midi librarys such as pythonmidi .经过搜索,我发现了一些 python midi 库,例如pythonmidi However, most of them can only create and read MIDI file without playing function.然而,他们中的大多数只能创建和读取 MIDI 文件,而不播放 function。 I would like to find a python midi library including playing method.我想找到一个包含播放方法的 python midi 库。 Any recommendations?有什么建议吗? Thanks!谢谢!

The pygame module can be used to play midi files. pygame 模块可用于播放midi 文件。

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

See the example here:请参阅此处的示例:

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

a whole bunch of options available at:一大堆选项可用:

http://wiki.python.org/moin/PythonInMusic 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也可以在这里修改以适合您的目的: http : //xenon.stanford.edu/~geksiong/code/playmus/playmus.py

Just to add a minimal example (via DaniWeb ):只是添加一个最小的例子(通过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

pretty_midi can generate the waveform for you, you can then play it with eg IPython.display.Audio 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)

Use pygame to play your midi file.使用 pygame 播放您的 MIDI 文件。 Examples are here or here例子在这里这里

I find that midi2audio works well.我发现midi2audio效果很好。

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

On macOS, you can use the pyObjC library to access the OS's own MIDI handling routines.在 macOS 上,您可以使用 pyObjC 库来访问操作系统自己的 MIDI 处理例程。 This script will play midi files given as arguments.此脚本将播放以 arguments 给出的 MIDI 文件。

#!/usr/bin/env python3

from AVFoundation import AVMIDIPlayer
from Foundation import NSURL
import time
import sys

def myCompletionHandler():
    return

def playMIDIFile(filepath):
    midiFile = NSURL.fileURLWithPath_(filepath)
    midiPlayer, error = AVMIDIPlayer.alloc().initWithContentsOfURL_soundBankURL_error_(midiFile, None, None)
    if error:
        print (error)
        sys.exit(1)
    MIDItime = midiPlayer.duration()
    midiPlayer.prepareToPlay()
    midiPlayer.play_(myCompletionHandler)
    if not midiPlayer.isPlaying:
        midiPlayer.stop()
    else:
        time.sleep(MIDItime)
    return  
    
if __name__ == "__main__":
    for filename in sys.argv[1:]:
        playMIDIFile(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM