Wednesday, 9 June 2010

Sound and Color in a C++ Console Program


Sound and Color in a C++ Console Program
Sound in Console Programs
Add the following code with the includes at the top of the program.

#include
#include other files as needed…
#include
#pragma comment(lib, "winmm.lib")
using namespace std;

Call Window’s PlaySound function, given filename.wav existing in the executable’s folder.

PlaySound("filename.wav", NULL, SND_ASYNC);

The sound plays until it is finished, the program terminates (so you might need to add system("pause")), or

PlaySound(NULL, NULL, NULL);

The SND_ASYNC parameter causes the function to return immediately after launching the sound.  The sound will endlessly repeat with

PlaySound("filename.wav", NULL, SND_ASYNC | SND_LOOP);

We can add the sound file to the executable so that the sound file does not have to accompany the executable as a separate file.  To do this, open the Solution Explorer using the View menu, right click on the Project folder in the Solution Explorer window, and choose Add Resource, importing the sound file.  (You will need to change the Files of Type field of the Open dialog to be WAV files and you will need to close the window of gibberish that appears.)  Now you can play the captured sound with

PlaySound(LPCSTR(101), NULL, SND_RESOURCE | SND_ASYNC);

To refer to your sounds as something more meaningful than LPCSTR(101), LPCSTR(102), …, right click on the .rc file in the Solution Explorer, open with Source Code (Text) Editor, and find the following line

IDR_WAVE1          WAVE       "filename.wav"

Change it to

my_sound_name          WAVE       " filename.wav"

Now you can

PlaySound("my_sound_name", NULL, SND_RESOURCE | SND_ASYNC);


Color in Console Programs
Set the default console foreground and background colors with

system("color ##");

The ## indicates two hexadecimal digits, the first corresponding to the background and the second to the foreground, as follows.

    0 = Black     8 = Gray
    1 = Blue       9 = Light Blue
    2 = Green     A = Light Green
    3 = Aqua      B = Light Aqua
    4 = Red        C = Light Red
    5 = Purple    D = Light Purple
    6 = Yellow   E = Light Yellow
    7 = White     F = Bright White

If no argument is given, this command restores the color to what it was when the window was opened.

No comments:

Post a Comment