要Play MP3,最简单的方法是使用API 函数mciSendCommand.
以下代码在VS2005下编译通过.在VS2005以下的版本要将IN DWORD_PTR类型替换为DWORD.
首先包含头文件:
#include <Mmsystem.h> //Support to play mp3.
#include <Digitalv.h>
#pragma comment(lib,"Winmm.lib")
以下是播放代码:
//Get program directory
CString strPath;
TCHAR szFull[_MAX_PATH];
TCHAR szDrive[_MAX_DRIVE];
TCHAR szDir[_MAX_DIR];
::GetModuleFileName(AfxGetInstanceHandle(), szFull, sizeof(szFull)/sizeof(TCHAR));
_tsplitpath_s(szFull,szDrive,sizeof(szDrive),szDir,sizeof(szDir),NULL,NULL,NULL,NULL);
//_tsplitpath(szFull, szDrive, szDir, NULL, NULL);
_tcscpy_s(szFull, szDrive);
_tcscat_s(szFull, szDir);
strPath = CString(szFull);
strPath+="1.mp3";
UINT wDeviceID; //device id
MCIERROR mciError; //
MCI_DGV_PLAY_PARMS mciPlay; //
MCI_DGV_OPEN_PARMS mciOpen;
mciOpen.lpstrDeviceType=_T("mpegvideo"); //Device Type
mciOpen.lpstrElementName=strPath.GetBuffer(); // cstring StrPath is full path of your mp3 file.
mciError=mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE|MCI_OPEN_ELEMENT,(IN DWORD_PTR)&mciOpen); //open device.
wDeviceID=mciOpen.wDeviceID;
mciError=mciSendCommand(wDeviceID, MCI_PLAY, MCI_DGV_PLAY_REPEAT,(IN DWORD_PTR)&mciPlay); //play mp3 file
如果要关闭: mciSendCommand(wDeviceID,MCI_CLOSE, NULL,NULL);
如果要停止: mciSendCommand(wDeviceID,MCI_STOP, NULL,NULL);