雑感等

音楽,数学,語学,その他に関するメモを記す.

pythonでmidiメッセージ送信

pythonのライブラリmidoを使用してリアルタイムにmidiメッセージを送信する.

以下のプログラムでは,ランダムな音高・音価・サステインペダルの踏み度合いを送信する.

pianoteqのstandaloneとloopMIDIも合わせて使っている.

import mido
import time
import numpy as np

ports = mido.get_output_names()
midi_port_name = ports[1]
time.sleep(1)
with mido.open_output(midi_port_name) as outport:
    outport.reset()
    time.sleep(1)


    def sustain_off():
        outport.send(mido.Message("control_change", channel=0, control=64, value=0, time=1))
        pass


    def sustain_on():
        outport.send(mido.Message("control_change", channel=0, control=64, value=127, time=1))
        pass


    def sustain(value):
        outport.send(mido.Message("control_change", channel=0, control=64, value=value, time=1))
        pass


    sustain_on()
    for n in range(1000):
        print(n)
        note = np.random.randint(21, 108 + 1)
        # vel_a = 2  # 夜用
        # vel_b = 12  # 夜用
        vel_a = 1.5
        vel_b = 1.5
        velo_on = round(np.random.beta(vel_a, vel_b) * 127)  # 朝用
        velo_off = round(np.random.beta(vel_a, vel_b) * 127)  # 朝用
        # dura = np.random.gamma(16 / 1.5, 0.2 * 1.5)  # 夜用
        dura = np.random.gamma(1, 0.2)  # 朝用
        sust = round(np.random.beta(0.8, 0.2) * 127)

        sustain(sust)
        time.sleep(0.01)
        outport.send(mido.Message("note_on", channel=0, note=note, velocity=velo_on, time=1))
        time.sleep(dura)
        outport.send(mido.Message("note_off", channel=0, note=note, velocity=velo_off, time=1))
        pass
    time.sleep(3)
    sustain_off()

    time.sleep(1)
    outport.reset()
    pass