简体   繁体   中英

How to PlaySound in C++ using Windows API?

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.

Can someone help me?

My code is:

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

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

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 (eg, 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
That should be it. Let me know, thanks!

try adding -lwinmm to your compiler settings thingy. It worked for me. Just type that in the compiler options area and it will work.

你可以使用绝对路径并检查它是否是路径错误?

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

With the SND_ASYNC flag your program can (and it will) terminate immediatelly!

Try PlaySound("kenny g.WAV", NULL, SND_SYNC); first to see if it works.

你可以通过PlaySound(TEXT(“SystemStart”),NULL,SND_ALIAS)进行测试;

Speaking about the path, your data file should be where your executable is, not where your source file is, if the path is not absolute.

And yeah, this very question has been asked 9 years ago ;)

Just in case it is unresolved yet! You need to include the two header files mentioned in previous comments, link the project to the required lib and place the sound file in the same folder as your .exe file (in case you are not using the full path)

Try this code it works for me. Also For code::Block use winmm in linker settings.

#include <iostream>  
#include <windows.h>
#include <MMSystem.h>
 int main(){
PlaySound(TEXT("your file path.wav") , NULL , SND_SYNC) ;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM