Background Sound / Stopping Sound

Hey!

I have written a program with a function that displays text character by character at a steady rate. Now I wanted to make this program more realistic by playing a keyboard sound while the typing is going on. Well I can get the sound to play, but it's quite a long sound and has to play the whole thing before typing the next character. Is there any way to play the sound WHILE the characters are typing, and stop when the characters end?

I am using VC++ 2008 Express Edition, here is my code:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <windows.h>
using namespace std;

//allow use of PlaySound
#pragma comment( lib, "winmm" )


//timed message function
int timed_message(char message [], bool use_seconds, int time)
{
	//set the ammount of time to seconds instead of milliseconds
	if(use_seconds == true)
	{
		time = time*1000;
	}

	//main for loop
	for(int x = 0;x<=80;++x)
	{
		//check for end 1
		if(message[x] == '%')
		{	
			++x;
			//check for end 2
			if(message[x] == '$')
			{
				// [..STOP PLAYING SOUND HERE..]
				return EXIT_SUCCESS;
			} //end if
			else
			{
				--x;
			} //end else
		} //end if
		else
		{
			cout << message[x];
			PlaySound(TEXT("keyboard.wav"), NULL, SND_FILENAME);
			Sleep(time);
		} //end else
	} //end for

	//characters couldnt be displayed?
	return ERROR;
}

//main function
int main()
{
	timed_message("Hello, these words will appear at a steady rate.%$",
		true, 1);
	//keep the console open and exit
	cin.get();
	return EXIT_SUCCESS;

} //end main 





Oh and yeah, this code is probably really ugly, so any tips for making this more efficient, or less of a mess would be appreciated. :P
Last edited on
Check the documentation for PlaySound() at MSDN. I think there was a flag that made the sound play asynchronously. If not, then there was a non-blocking version of PlaySound().
Yes there was!

1
2
3
4
5
6
7
// . . .
if(sound_is_playing == false)
{
	PlaySound(TEXT("keyboard.wav"), NULL, SND_FILENAME | SND_ASYNC);
	sound_is_playing = true;
}
// . . . 


to play the sound, and

1
2
3
4
5
6
7
// . . .
if(message[x] == '$')
{
	PlaySound(TEXT("MyAppSound"), NULL, SND_APPLICATION);
	return EXIT_SUCCESS;
}
// . . . 


to stop it, thanks for the suggestion.

Topic archived. No new replies allowed.