c++audiobeep

beep sound till any input


I am making a Quiz program. So what I want is whenever any question in presented before the user, then he has 30 seconds to answer it. And in these 30 seconds I want the beep sound ('\a') at an interval of 1 second. Now I want is that this beep sound should stop as soon as the user enters any input. I have created this small function to produce the beep sound for 30 sec void beep(){ for(int i=0;i<30;i++){cout<<"\a"; Sleep(1000); } } But I don't know how to stop it as soon as the user enters his/her answer because once I call it nothing can be done until its over. Can anyone give any workaround for it?


Solution

  • Disclaimer: I'm not a Windows programmer, I don't know if this is good style or even if it will compile or work. I can't test it here. However, as no one else has given a solution, it's a starting point. I'll edit this answer as I learn more, and hopefully someone who knows more about this will turn up.

    Edit: I faked out _kbhit() to a trivial function returning false, and it at least compiles and looks like it runs ok

    Edit: Ok I do have ms visual studio at work, I just never use it. The code as it is right now compiles and works (I suspect the timing is off though).

    Edit: Updated it to immediately read back the key that was hit (rather than waiting for the user to hit enter).

    This is the important function: http://msdn.microsoft.com/en-us/library/58w7c94c%28v=vs.80%29.aspx

    #include <windows.h>
    #include <conio.h>
    #include <ctime>
    #include <iostream>
    #include <string>
    
    int main()
    {
        time_t startTime, lastBeep, curTime;
        time(&startTime);
        lastBeep = curTime = startTime;
        char input = '\0';
    
        while ( difftime(curTime,startTime) < 30.0 )
        {
            if ( _kbhit() ) // If there is input, get it and stop.
            {
                input = _getch();
                break;
            }
            time(&curTime);
            if ( difftime(curTime,lastBeep) > 1.0 ) // More than a second since last beep?
            {
                std::cout << "\a" << "second\n" << std::flush;
                lastBeep = curTime; // Set last beep to now.
            }
        }
        if ( input )
        {
            std::cout << "You hit: \"" << input << "\"\n" << std::flush;
        }
    
        return 0;
    }