ウィンドウズで音楽を鳴らすプログラム

Tweet


Win32APIを利用してBGMや効果音を再生するプログラムのサンプルソースコードを紹介します.C/C++でのプログラムで,Windows.hを使ったものです.bgm.wavとbell.wavは各自で用意してください.

#include <stdio.h>
#include <conio.h>
#include <Windows.h>
#pragma comment (lib, "winmm.lib")

int main()
{
    char bgmfilename[] = "bgm.wav";
    char bellfilename[] = "bell.wav";
    char ch;

    PlaySound(bgmfilename, NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);

    MCI_OPEN_PARMS bellopen;
    bellopen.lpstrDeviceType = "WaveAudio";
    bellopen.lpstrElementName = bellfilename;
    mciSendCommand(NULL, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD)&bellopen);

    printf("[ESC] End, [SPACE] Bell\n");
    for (;;) {
        ch = _getch();
        if (ch == 0x1B) break;
        if (ch == ' ') {
            mciSendCommand(bellopen.wDeviceID, MCI_SEEK, MCI_SEEK_TO_START, 0);
            mciSendCommand(bellopen.wDeviceID, MCI_PLAY, 0, 0);
        }
    }
    mciSendCommand(bellopen.wDeviceID, MCI_CLOSE, 0, 0);
    PlaySound(NULL, NULL ,0);
    printf("Press any key\n");
    _getch();
    return 0;
}


もどる