Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Beep sound in C on Windows?

Tags:

c

windows

audio

I am trying to make a program which includes a beep noise. I work on a 32 bit Windows Vista. I am using the Code::Blocks IDE which runs on a GNU compiler. My sample code is -

#include <stdio.h>
#include <windows.h>
#include <dos.h>

int main(void)
{
    Beep(750, 300);
    printf("\n \n \t This is a dummy program for Beep.");
    getch();

    return 0;
}

On the Internet I read that we could also use \a in printf to make a beep. I tried that but it is not working. I checked my speakers and sound card. Everything is perfect but I hear no beep. Even the method I displayed in my sample code does not work.

like image 288
Ashish Ahuja Avatar asked Apr 07 '15 14:04

Ashish Ahuja


2 Answers

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.

like image 152
Damian Yerrick Avatar answered Sep 30 '22 20:09

Damian Yerrick


MessageBeep(-1);

From the MSDN documentation:

MessageBeep function

Plays a waveform sound. The waveform sound for each sound type is identified by an entry in the registry.

BOOL WINAPI MessageBeep( _In_ UINT uType ); ... ...

Value for uType: 0xFFFFFFFF

Meaning: A simple beep. If the sound card is not available, the sound is generated using the speaker.


Also, and to my surprise, I've tested that. at least Windows 7 32 bits (and Windows Vista surely too) do some sort of emulation for the old 8253 I/O ports and the keyboard port, available to ring 3 processes, so the old implementation of sound() and nosound() should work. Unfornately, I haven't got any 32 bit machine available ATM so I cannot confirm this.

like image 32
mcleod_ideafix Avatar answered Sep 30 '22 20:09

mcleod_ideafix