Playing music for Windows programming

Tweet


Below is a sample source code of a program which plays sound and music using Win32API. This is a C/C++ program which use Windows.h. Sample program use bgm.wav and bell.wav which you have to set beforehand.

#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;
}


Back