如何使用 Windows API 在 C++ 中播放声音?

2021-12-18 00:00:00 winapi c++ playsound

我尝试在我的编码中播放音乐文件,但失败了.我的音乐文件在保存 .cpp 文件的同一个文件夹中.

I try to play a music file in my coding, but failed. I have my music file in the same folder which save .cpp file.

有人可以帮我吗?

我的代码是:

#include <iostream>  
#include <windows.h>

int main() { 
    PlaySound("kenny g.WAV", NULL, SND_ASYNC);    
}

推荐答案

您需要使用绝对路径,确保您发送的是文件名(使用 SND_FILENAME 标志),并暂停程序足够长的时间以播放声音文件(例如,使用 getchar()).您需要在项目设置中链接 winmm.lib 库,并在标题中链接 #include windows.h 和 mmsystem.h.

You need to use the absolute path, make sure that you're sending a filename (use SND_FILENAME flag), and pause the program long enough to play the sound file (e.g., use getchar()). You need to link the winmm.lib library in your project settings, and #include windows.h and mmsystem.h in the header.

#include <windows.h>
#include <mmsystem.h>

int main() {
    PlaySoundA((LPCSTR) "C:\kenny g.WAV", NULL, SND_FILENAME | SND_ASYNC);
    getchar();
}

API:http://msdn.microsoft.com/en-us/library/ms712879(VS.85).aspx
应该是这样.让我知道,谢谢!

API: http://msdn.microsoft.com/en-us/library/ms712879(VS.85).aspx
That should be it. Let me know, thanks!

相关文章