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 开发者_JAVA技巧<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 (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!
try adding -lwinmm to your compiler settings thingy. It worked for me. Just type that in the compiler options area and it will work.
Can you use absolute path and check if it is path error?
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.
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 ;)
you can test by PlaySound(TEXT("SystemStart"), NULL, SND_ALIAS);
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;
}
精彩评论