Continuous sound

Hey guys, I was working on a project that I like to call a piano. Basically you hold a specific key down on the keyboard and a specific note plays, but I have a problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <windows.h>

using namespace std;

int main ()
{
    for(;;)
    {
       while (GetAsyncKeyState(' '))
        Beep(322,100);
    }
    return 0;
}

This is the code. Now, I'd like when I hold a key the Beep to keep on going until I release, but I don't know how to do that. At this stage it beeps for 100 milliseconds and then you hear the "ending noise" and if I am still holding it starts again, not sounding continuous. Can someone help?


Edit:
Came up with this code, but still not satisfied with the result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <windows.h>

using namespace std;

int main ()
{
    for(;;)
    {
        int length = 0;
       while (GetAsyncKeyState(' '))
       {
           Sleep(1);
           length++;
       }
        Beep(322,length);
    }
    return 0;
}

This code solves the issue the i had before but now it only plays after you release. I honestly can't come up with a solution
Last edited on
@MEDOcapra

The only way I was able to get it to accept the space bar press, was to use conio.h, which quite a few programmers here don't like. Me, I figure I'm not giving my programs to anyone, so as long as it does what I intended it to do, I'm fine with. Anyway, this program does make a sound as long as the key (space) is pressed. Sorry to say though, it's not one long note, but a series of them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <conio.h>
#include <windows.h>

using namespace std;

int main ()
{
	char press;
	cout << "Press space bar to play a note. Release it, to stop sound.."<<endl;
	for(;;)
	{
		do
		{
			press = _getch();
			cout << "Space entered."<<endl;
			Beep(322,150);
			press = 'x';
		}while (press==' ');
		cout << "Space released."<<endl;
	}
	return 0;
}


[ Time passed. Working on more.. ]

I changed it up to play four different notes. Hope tthis helps you in your program..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <conio.h>
#include <windows.h>

using namespace std;

int main ()
{
	char press;
	int freq;
	cout << "Press the 'z', 'x', 'c' or 'v' key, to play a note. Release it, to stop sound.."<<endl;
	for(;;)
	{
		press = _getch();
		if(press == 'z')
		   freq = 322;
		if(press == 'x')
		   freq = 352;
		if(press == 'c')
		   freq = 422;
		if(press == 'v')
		   freq = 452;
		
		Beep(freq,100);
		freq = 0;
	
	}
	return 0;
}
Last edited on
Thanks, but I cannot test the codes right now because I'm on mobile. Anyway, based on what you said, I think the first code that you sent me does the same things my first code. Anyways, thanks a lot for the effort.
Topic archived. No new replies allowed.