Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

winapi - 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);    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...