How to PlaySound in C++ using Windows API?

user189748 picture user189748 · Oct 14, 2009 · Viewed 51.9k times · Source

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);    
}

Answer

Luis B picture Luis B · Oct 14, 2009

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!