Home > Software engineering >  How Would I include a beep sound without causing a delay in C ?
How Would I include a beep sound without causing a delay in C ?

Time:02-25

I've made a small countdown and every 5 seconds it should make a beep sound but im not sure how to do this without an extra delay. How can i avoid this? I cant find anything that answers this specific question.

#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
    int N;
    cin >> N;
    while (N > 0)
    {
        Sleep(1000); 
        cout << N << endl;
        if(N%5==0) 
        {
            cout << "beep" << endl;
            Beep(1000, 500);
        }
        N--;
    }

}

CodePudding user response:

You can use MessageBeep() for your purpose. Its syntax is like this:

BOOL MessageBeep(
  [in] UINT uType
);

And its use is something like this:

MessageBeep(uType);

Read up about it on MSDN to find out more about all of the possible arguments.

For your code, you can do something like this:

#include <iostream>
#include <Windows.h>

int main()
{
    int N;
    std::cin >> N;
    while (N > 0)
    {
        Sleep(1000);
        std::cout << N << std::endl;
        if (N % 5 == 0)
        {
            std::cout << "beep" << std::endl;
            MessageBeep(0xFFFFFFFF); // Replace 0xFFFFFFFF with whatever value you want
        }
        N--;
    }
}

Also, consider not using the following line in your code:

using namespace std;

It's considered as bad practice. This is because, for example, if 2 namespaces contain 2 functions with the same name and parameters, and if you write 'using namespace' for both of the namspaces then the compiler won't be able to figure out which function to use, and thus your application won't work.

CodePudding user response:

On Windows you can play a simple sound asynchronously using the PlaySound Win32 call like the following, where by "asynchronously" we mean without pausing:

PlaySound(
    reinterpret_cast<LPCTSTR>(SND_ALIAS_SYSTEMDEFAULT), 
    hInstance, 
    SND_ASYNC | SND_ALIAS_ID
);

SND_ALIAS_ID means you are not providing a .wav file path or resource in the first parameter but instead are just specifying an ID of a canned sound built into Windows. These canned sounds are all the same chime, not really a beep, on Windows 10, but you could also embed a beep sound into you application as a .wav resource and use that.

To use PlaySound you will need to be linking to Win32 libraries, in particular "Winmm.lib", I believe.

  • Related