问题
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);
}
回答1:
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
That should be it. Let me know, thanks!
回答2:
try adding -lwinmm to your compiler settings thingy. It worked for me. Just type that in the compiler options area and it will work.
回答3:
Can you use absolute path and check if it is path error?
Ex: PlaySound("C:\\kenny g.WAV", NULL, SND_ASYNC);
回答4:
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.
回答5:
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 ;)
回答6:
you can test by PlaySound(TEXT("SystemStart"), NULL, SND_ALIAS);
回答7:
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)
回答8:
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;
}
来源:https://stackoverflow.com/questions/1565439/how-to-playsound-in-c-using-windows-api