C++PlaySound函数,如何用PlaySound函数来播放一个声音资源文件?

2025-04-14 09:56:50
推荐回答(1个)
回答1:

#include "stdafx.h"
#include 
#include 
#include 
#include "resource.h"
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
    int soundResourceID = IDR_WAVE1;
     HINSTANCE hInst = NULL;
     try{
      BOOL bRtn;
      LPVOID lpRes;
      HANDLE  hRes;
      HRSRC hResInfo;
      // Find the WAVE resource.
      hResInfo = FindResource(hInst, MAKEINTRESOURCEW(soundResourceID), L"WAVE");
      if (hResInfo == NULL)
           throw std::exception("Cannot find the resource");
      // Load the WAVE resource.
      hRes = LoadResource(hInst, hResInfo);
      if (hRes == NULL)
          throw std::exception("Cannot load the resource");
      // Lock the WAVE resource and play it.
      lpRes = LockResource(hRes);
      if (lpRes != NULL) {
           bRtn = sndPlaySoundW((wchar_t*)lpRes, SND_MEMORY | SND_SYNC |
                SND_NODEFAULT);
          UnlockResource(hRes);
          MessageBoxW(NULL, L"Playing sound", L"", 0);
      }
      else
           bRtn = 0;
          // Free the WAVE resource and return success or failure.
          FreeResource(hRes);
     }
     catch (const std::exception& e)
     {
          MessageBoxA(NULL, e.what(), "", 0);
     }
    
     return 0;
}

需要注意 不要忘记代码中的 #include 这几项,还有需要在项目(不是解决方案)的属性页面中进行如上图的设置 在 Configuration Properties->Linker->Input->Additional Dependences 中加入 winmm.lib .

 

另外补充一下如何打开 项目属性页面,如下图所示

我还上传了源代码,请查看附件

对于您的问题 请参考 https://msdn.microsoft.com/en-us/library/dd743679(v=vs.85).asp