WindowsでMIDIを鳴らすには

すでにファイルになっているMIDIを鳴らすのではなくて、プログラム内でドとかミとか指定して鳴らす方法を調べてみました。
結論から言うと、midiOutなんたらってAPIを使えばできます。とりあえずC言語(Cygwingcc)のサンプル。ピアノの音でCの和音(ド、ミ、ソ)が3秒間鳴ります。ふむ。midiOutShortMsgを使っている分にはそんな難しくなさそう。

#include <stdio.h>
#include <windows.h>

#define MIDIMSG(stat, data1, data2) \
    (DWORD)(stat | (data1 << 8) | (data2 << 16))

static void
error(char *mesg, UINT ret)
{
    fprintf(stderr, "Error: %s(%d)\n", mesg, ret);
    exit(1);
}

static void
send_note(HMIDIOUT hMidi, UCHAR stat, WORD note, WORD vol)
{
    UINT ret;

    if ((ret = midiOutShortMsg(hMidi, MIDIMSG(stat, note, vol))) != 0)
	error("midiOutShortMsg", ret);
}

int
main(int argc, char *argv[])
{
    UINT ret;
    HMIDIOUT hMidi;
    
    if ((ret = midiOutOpen(&hMidi, MIDIMAPPER, 0, 0, 0)) != 0)
	error("midiOutOpen", ret);

    send_note(hMidi, 0x90, 0x3c, 0x40); /* C */
    send_note(hMidi, 0x90, 0x40, 0x40); /* E */
    send_note(hMidi, 0x90, 0x43, 0x40); /* G */

    sleep(3);

    send_note(hMidi, 0x90, 0x3c, 0); /* C */
    send_note(hMidi, 0x90, 0x40, 0); /* E */
    send_note(hMidi, 0x90, 0x43, 0); /* G */
    
    if ((ret = midiOutClose(hMidi)) != 0)
	error("midiOutClose", ret);

    return 0;
}

参照: