使用Python播放MIDI音符

转载自我的个人网站 https://wzw21.cn/2022/01/11/play-midi-note/

目录

使用 Python 播放 MIDI Note

方法一:使用music21

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

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()
上一篇:Aop限流实现解决方案


下一篇:「Note」高斯消元(未完)