Playsound() overlap

I have a program that makes a ding sound when you press the mouse button.
However, it waits for the sound file to finish before it can play it again.
I was wondering how I could allow the same sound to overlap over it self, so when clicking fast, it will ding at every click.

Very small amount of code:
1
2
3
4
5
6
7
#include <Windows.h>
#include <MMsystem.h>
int main(){
for(;;){
if ( GetAsyncKeyState ( VK_LBUTTON )){
PlaySound(TEXT("ding.wav"), NULL, SND_FILENAME);
}}}
Maybe you want to pass the SND_ASYNC flag.

 
PlaySound(TEXT("ding.wav"), NULL, SND_FILENAME | SND_ASYNC);

http://msdn.microsoft.com/en-us/library/dd743680%28v=vs.85%29.aspx
hmm now it just started dinging uncontrollably. it goes slower if Sleep(xx) is added in the loop. maybe it has something to do with it being a loop?

not quite the desired effect.
the original did this:

click click click
ding starts - finishes ding starts - finishes ding starts - finishes

sequential.

with async it did this:

click
ddddddddddddddddddddddddddddddd

i want this to happen:

rapid clicks
___ding
_____ding
_______ding
_________ding
Last edited on
Problem is that PlaySound is called repeatedly for as long as the button is pressed down. You only want to run it once when the key is pressed down. If you add a variable to keep track of if the button is down you could use it to make sure that the sound only playes once for each press.
1
2
3
4
5
6
7
8
9
10
11
bool button_down = false;
for(;;) {
	if ( GetAsyncKeyState ( VK_LBUTTON )) {
		if (!button_down) {
			PlaySound(TEXT("ding.wav"), NULL, SND_FILENAME | SND_ASYNC);
		}
		button_down = true;
	} else {
		button_down = false;
	}
}


This is not perfect. If the user press the button very quickly so that there is no call to GetAsyncKeyState while the button is pressed down the program will completely miss the click. For a more robust solution you should probably look into event polling/listeners but I don't really know anything about those things when it comes to the WinAPI.
that is exactly what I wanted. thanks!
Topic archived. No new replies allowed.