How to use PlaySound in C

Ashish Ahuja picture Ashish Ahuja · May 2, 2015 · Viewed 10.5k times · Source

I am using code::blocks IDE which runs on GNU GCC compiler. In my project I want to play a .wav sound file in C. I tried to play a .wav sound file with a function called PlaySound. When I compiled the code code::blocks gave me an error - PlaySoundA not declared. My code is-

#include <stdio.h>
#include <windows.h>
#include <windowsx.h>
#include <mmsystem.h>

int main(int argc, char *argv[])
{
  PlaySound("C:\Snakes and Ladders\snake.wav",NULL,SND_SYNC | SND_LOOP | SND_FILENAME);
  return 0;
}

I checked my path twice. I read about this function on the internet and as per me I am using it in the correct way.

In Google, I read that the function exists in a file called winmm.lib. So I put a line of code after all the headers. It was-

 #pragma comment (lib , "winmm.lib")

I also added the name winmm.lib to the additional dependencies of code::blocks. So now when I compile the code it gives me another error - winmm.lib not found. Can somebody please tell me how to use PlaySound correctly.

Answer

Jamesthe1 picture Jamesthe1 · Jun 7, 2018
  1. Remove the pragma comment
  2. Double the backslashes. The backslash is an escape character
  3. Compile with the winmm library. Using MinGW, the command would look like this:

    gcc foo.c -o foo.exe -lwinmm