How to make a Beep sound in C on Windows?

The C standard recommends that writing '\a' to standard output produce an audible or visible alert signal, but it will not work if standard output is redirected. Likewise, some newer computers lack the PC beeper on which Windows Beep() and some terminals rely. To cause a Windows PC to play an alert sound in a desktop application, you can call the Windows-specific MessageBeep function, which plays a sound "asynchronously" (in the background while your program continues to run). The user can configure which sound is associated with each of these four values in the Sound control panel.

#include <windows.h>

/* Include one of these in a function */
MessageBeep(MB_OK);              /* play Windows default beep */
MessageBeep(MB_ICONINFORMATION); /* play asterisk sound */
MessageBeep(MB_ICONQUESTION);    /* play question sound */
MessageBeep(MB_ICONWARNING);     /* play warning sound */

MessageBeep() is defined in User32.dll, so if this gives you link errors, make sure you're linking to the corresponding import library. In MinGW GCC (the compiler in Code::Blocks), add -lUser32 to the list of libraries passed to the linker.

Tags:

Windows

C

Audio