使用 Python 播放 MIDI Note

方法一:使用music21

1
2
3
4
5
6
7
8
9
10
11
12
import music21 as m21

def play_note(pitch="C4", length=2, velocity=127, instrument='Piano'):
note_1 = m21.note.Note(pitch, quarterLength=length)
note_1.volume.velocity = velocity
stream_1 = m21.stream.Stream()
if instrument == 'Piano':
stream_1.append(m21.instrument.Piano())
# stream_1.insert(0, m21.instrument.Piano())
stream_1.append(note_1)
s_player = m21.midi.realtime.StreamPlayer(stream_1)
s_player.play()

注意该方法也需要安装pygame

方法二:使用pygame

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pygame.midi as pm

pm.init() # init midi player
player = pm.Output(0)
BPM = 120

def play_note(pitch=60, length=2, velocity=127, instrument='Piano'):
if instrument == 'Piano':
player.set_instrument(0)
player.note_on(pitch, velocity)
time.sleep(length * 60 / BPM)
player.note_off(pitch, velocity)

del player
pm.quit()