How can I play a sound in C++?

It seems to be easy, but something is wrong with it... :-(
As I know, the PlaySound() function is part of windows.h, so not needed any other file, e.g. mmsystem.h(?).
But Code::Blocks throw the following error messages when I try to run my code:
obj\Debug\main.o||In function `Z15WindowProcedureP6HWND__jjl@16':|
F:\progsetup\codeblocks-17.12mingw-nosetup\sajatok\ablakosrajz\Rajz\main.cpp|173|undefined reference to `PlaySoundA@12'|
||error: ld returned 1 exit status|

1
2
3
4
5
  case WM_KEYDOWN:
            switch (wParam)
            {
                case VK_CONTROL: PlaySound(TEXT("shoot.wav"), NULL, SND_FILENAME | SND_SYNC);
                break;
You need to add the library mmsystem.lib to the project
Sorry on Code::Blocks is probably has a different name.
Yes , it's called libwinmm.a
Last edited on
Last time I compiled windows code with GCC I had the same problem with PlaySound function,
even after linking libwinmm it didn't work.

this is just a beginning btw, you will encounter many such WINAPI problems when compiling with non native compilers.
With Code::Blocks 20.03, the steps should be similar with 17.12:

Project->Build options->Linker settings

Select "Add", enter the lib filename (libwinmm.a) and select OK. Rebuild the target. If, repeat IF, the sound file is in the correct location running the app should play the sound.

1
2
3
4
5
6
#include <windows.h>

int main()
{
   PlaySound(TEXT("test.wav"), NULL, SND_FILENAME);
}


Location is key to getting the sound file to play properly.
Thanks, guys, and especially for you, Furry Guy! Now the program can play the sounds.
But I realized, that in this case the program stopped for a little time, e.g. I couldn't move with the controlled player figure.
I know, these routines aren't the right functions for creating a little game, but is it possible to play a sound without cause a lag, or should I use a multimedia library (SDL, SFML or similar, that I would not like)?
Last edited on
The Windows multi-media system really is not designed to work with games, though simple 2D windowed games are possible. They can be quite fun even with the limitations GDI and the multi-media system have.

You can use a cross-platform library, or try DirectX if you are creating games for Windows and Windows affiliated mobile systems.

Or you could ramp up to using a game engine that would handle a lot of the nitty gritty details for you. Especially helpful for that might be upgrading to Visual Studio 2019. That IDE has a lot of wizards and templates for creating games with DirectX, Unity, Unreal or Cocos.
https://visualstudio.microsoft.com/vs/features/game-development/

I personally have not really used those features much, but what I have played around with VS2019 does reduce the frustration factor considerably when getting a game app framework started.

An old Sams book (2004) I have in my library - Beginning Game Programming - delves into creating Windows games with GDI and the multi-media library. The code examples create a minimalist game engine step by step.
https://www.amazon.com/gp/product/0672326590/

The code requires some minor tweaks for newer Windows versions like Win 10. I rebuilt the games' sources about a year ago for x86 and x64 executables after making some tweaks and changes to enhance C++ container usage.

I found this to be quite a useful book and accompanying code examples.
BTW, do consider updating your C:B install to 20.03. The included MinGW compiler is newer and the IDE layout has been IMO improved to be more user friendly. There are more compiler flags available with 20.03 that IIRC 17.12 doesn't support. Such as C++17 support as well as being able to compile to x86 or x64 executables.
I would like avoid using of other libraries and only use the multimedia system of the device on my program run - if possible.
Maybe can I preload the sound file with the SND_MEMORY value of PlaySound() and so play it without lag? But I don't understand the method of preloading of files in C++. :-(
>I would like avoid using of other libraries and only use the multimedia system of the device on my program run - if possible.
Why?

Also Furry Guy's last post was just talking about the IDE/compiler, not libraries. Edit: Oh you were referring to the post above that.

Anyway... for playing a sound, the term you're looking for is "non-blocking" or "asynchronous".
https://stackoverflow.com/questions/41421313/make-playsound-non-blocking
Last edited on
Thank you very much, Ganado! It works!
Now everything works smooth in my program. So, this is the piece of code:
PlaySound(TEXT("shoot.wav"), NULL, SND_FILENAME | SND_ASYNC);
I would like avoid using of other libraries and only use the multimedia system of the device on my program run - if possible.

You do realize the libraries you are wanting to avoid use the built-in basic graphic and multi-media system of the OS, hiding all the tedious details in the framework(s), as well enhance the features of the systems to do things that would require a LOT of code to replicate. 3D graphics, for instance. Playing music other than midi files for another.

BTW, if you are wanting to have sounds that don't seem to lag don't use SND_SYNC. SND_ASYNC is the flag you need.

1
2
3
4
5
6
7
8
9
#include <windows.h>
#include <cstdio>

int main()
{
   PlaySound(TEXT("test.wav"), NULL, SND_FILENAME | SND_ASYNC);

   getchar();
}

Why the getchar();? So the app is still running when the mmsystem asynchronously plays the sound. Without that flag, well, the timing is not guaranteed.

I am not trying to discourage you from using GDI and the mmsystem. I am just trying to let you know of the serious game related limitations built-in when using those older Windows technologies.

I gave you a link to an old Windows game programming book earlier. Consider buying it if you want to learn the steps of creating a game that uses those old technologies.

The book creates a neat little GDI/mmsystem game engine you can use to create your own 2D windowed games just by plopping the game engine source files into your new game project. C++ reuseability, YEAH!

I also suggest getting Visual Studio 2019 Community as well. It's free.
https://visualstudio.microsoft.com/downloads/

Trying to wrestle with Code::Blocks for Windows GUI apps can be irksome and frustrating. I know, I keep trying. Those little code snippets I created? A lot more work and skull sweat to get them to compile with C:B than MSVC.
Here's what's possible on modern Windows with the basics of Windows graphics and sound technologies.
http://www.filedropper.com/spaceout4

Compiled with MSVC for 32-bit, no additional MSVC DLLs needed. Just the exe and the midi file for background music. The graphics and sounds are embedded in the program file.
Wow, thank you, Furry Guy, everything is very helpful for me.
I think, C++ isn't the easiest programming language, but one of the most important languages, mainly in game development.
And can I make cross-platform games with this technique, e.g. an Android game too?
Hi,

I tried and worked for me.

1
2
3
4
5
6
7
8
9
10
11
#include <windows.h>
#include <mmsystem.h>
#include <cstdio>

int main()
{
	cout<<"Test PlaySound"<<endl;
	PlaySound(TEXT("test.wav"), NULL, SND_FILENAME | SND_ASYNC);

        getchar();
}


Don't forget to link 'winmm.lib'.

can I make cross-platform games with this technique

Not with Windows' antique GDI and multi-media technologies. To be cross-platform would require a 3rd party library. You'll need to bury your dislike of using non-Windows libraries if you want to create apps on systems other than Windows. Android is not Windows.

You could leverage a 3rd party cross-platform game engine such as Unity or Unreal, or go with a "basic" cross-platform multi-media library SFML or SDL and mash together your own game engine bare-boned style.

One thing to note, using Visual Studio 2019 instead of Code::Blocks would make it easier to go cross-platform game creation. Especially if you decide to take advantage of a pre-coded game engine. There are "plugins" you can install in MSVC that make game project creation, testing and debugging much easier.

VS 2019 has a free edition, Community. Even the Community edition can do cross-platform for iOS and Android.
https://visualstudio.microsoft.com/vs/compare/

Game creation these days is not a simple weekend type project. It takes some seriously mad programming and multi-media skills to create enjoyable and fun "let's play that again" games. People expect a lot out of their games, even the free ones.
akash16 wrote:
Don't forget to link 'winmm.lib'.

That won't work with a GCC/MinGW type compiler such as the one that can be bundled with Code::Blocks. C::B is the IDE the OP is using.

The library needed for GCC/MinGW is "libwinmm.a."

Including <mmsystem.h> is not required no matter what Windows app compliant compiler used, it is included with <windows.h>.
I think, C++ isn't the easiest programming language

The game engine used to create that game is class based for all the nitty-gritty details of managing the multi-media resources and OS related functioning. Rewriting the game code is generally contained to just one file to manage the sound and sprite processing unique to each game. Sometimes a derived class is mashed up to do some enhancements to a part of the game engine system. "Alien" sprites for a space game, for example.

Well-written reusable game engine code can make creating different games easy and quick to do.
@Furry Guy.
Thanks.
Hello Furry Guy!

I have download and tried the SpaceOut4 game: very interesting and funny! Can it play more than one sound simultaneously?
Do you know LazyBlocks? It is a Tetris-clone in C++ and the only C++ game I have with source code, but it seems it using SDL, not only Win32GUI.
Topic archived. No new replies allowed.