Beep sample

A question came in today about the Beep(…) API1 not being able to set the frequency of the beep that was generated. In order to confirm that it worked I whipped up a quick sample which would take the frequency (and duration) on the command line. Source and binaries attached.

For fun I added the ability to pass in the frequency using Scientific pitch notation. Note that A4 is about 431 Hz using this scale, rather than the more standard 440 Hz2.

for (int i = 1; i + 1 < argc; i += 2) {
     ULONG frequency;
     HRESULT hr = HertzFromScientificPitchNotation(argv[i], &frequency);
     if (FAILED(hr)) { return -__LINE__; }

     ULONG duration;
     hr = UlongFromString(argv[i + 1], &duration);
     if (FAILED(hr)) { return -__LINE__; }

     if (!Beep(frequency, duration)) {
         LOG(L"Beep(%u, %u) failed: GetLastError() = %u", frequency, duration, GetLastError());
         return -__LINE__;

So, for example, you can play a certain well-known tune via Beep() using this command:

>beep.exe C3 2000 G3 2000 C4 4000 E4 500 Eb4 3500 C3 500 G2 500 C3 500 G2 500 C3 500 G2 500 C3 2000

1 More on the Beep(…) API:

The official Beep(…) documentation

A couple of blog posts from Larry Osterman:
Beep Beep
What’s up with the Beep driver in Windows 7?

2 If you want the more standard pitch, change this line:

double freq = 256.0;

To this:

double freq = 440.0 * pow(semitoneRatio, -9.0); // C4 is 9 semitones below A4

Browse source

Download beep.exe

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s