Question
Play music with Media Control Interface(MCI)
Solution
1. Open MCI Device
2. Send a command to play music
3. Close MCI Device when finished
#include <iostream>
#include <iomanip>
#include <string>
#include <Windows.h>
using namespace std;
class MIDIPlayer
{
public:
MIDIPlayer() { _MIDIPlayID = 0; }
~MIDIPlayer(){ Close(); }
void Play(wstring musicName){
if(IsOpen()){
Close();
}
if(Open(musicName) != 0){
wcout << L"Couldn't open MIDI device" << endl;
return;
}
MCI_PLAY_PARMS mciPlayParms;
if(mciSendCommand(_MIDIPlayID, MCI_PLAY, 0, (DWORD_PTR)&mciPlayParms) != 0){
Close();
wcout << L"Couldn't play " << musicName << endl;
}
}
private:
bool IsOpen() {return _MIDIPlayID != 0; }
int Open(wstring musicName) {
int retCode = -1;
MCI_OPEN_PARMS mciOpenParms;
mciOpenParms.lpstrDeviceType = L"sequencer";
mciOpenParms.lpstrElementName = musicName.c_str();
retCode = mciSendCommand(NULL, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpenParms);
if(retCode == 0){
_MIDIPlayID = mciOpenParms.wDeviceID;
}
return retCode;
}
void Close(){
if(IsOpen()){
mciSendCommand(_MIDIPlayID, MCI_CLOSE, 0, NULL);
_MIDIPlayID = 0;
}
}
UINT _MIDIPlayID;
};
int main()
{
MIDIPlayer player;
player.Play(L"Music.mid");
cin.get();
return 0;
}