Here's a little christmas program:
- Code: Select all
#include <iostream>
#include <sstream>
#include <map>
#include <cstdlib>
#include <cmath>
#ifdef _WIN32
#include <windows.h>
#else
void Beep(float frequency, int duration=120)
{
std::ostringstream sstr;
sstr << "beep -f " << frequency << " -l " << duration;
system(sstr.str().c_str());
}
void Sleep(unsigned int milliseconds)
{
timespec t;
t.tv_sec = milliseconds / 1000;
t.tv_nsec = (milliseconds - t.tv_sec * 1000) * 1000000;
nanosleep(&t, NULL);
}
#endif
using namespace std;
int main (void )
{
map<std::string, float> theMap;
const std::string names[12] = {"c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b"};
std::ostringstream name;
for(int currentOctave = 0; currentOctave <= 9; currentOctave++)
{
float a_oct = 440.0 * pow(2, currentOctave - 4);
for(int i=0; i<12;i++)
{
name.str("");
name << names[i] << currentOctave;
float freq = a_oct * pow(2, (i-9)/12.0f);
theMap[name.str()] = freq;
//cout << name.str() << "=" << freq << endl;
}
}
theMap["p"] = 0;
cout << " * ,\n";
cout << " _/^\\_\n\
< >\n\
* /.-.\\ *\n\
* `/&\\` *\n\
,@.*;@,\n\
/_o.I %_\\ *\n\
* (`'--:o(_@;\n\
/`;--.,__ `') *\n\
;@`o % O,*`'`&\\ \n\
* (`'--)_@ ;o %'()\\ *\n\
/`;--._`''--._O'@;\n\
/&*,()~o`;-.,_ `\"\"`)\n\
* /`,@ ;+& () o*`;-';\\\n\
(`\"\"--.,_0 +% @' &()\\\n\
/-.,_ ``''--....-'`) *\n\
* /@%;o`:;'--,.__ __.'\\\n\
;*,&(); @ % &^;~`\"`o;@(); *\n\
/(); o^~; & ().o@*&`;&%O\\\n\
jgs `\"=\"==\"\"==,,,.,=\"==\"===\"`\n\
__.----.(\\-''#####---...___...-----._\n\
'` \\)_`\"\"\"\"\"`\n\
.--' ')\n\
o( )_-\\\n\
`\"\"\"` `\n";
string song = "c4,8,f4,8,f4,4,g4,4,f4,4,e4,4,d4,8,d4,8,\
d4,8,g4,8,g4,4,a4,4,g4,4,f4,4,e4,8,e4,8,\
e4,8,a4,8,a4,4,a#4,4,a4,4,g4,4,f4,8,d4,8,c4,4,c4,4,d4,8,g4,8,e4,8,f4,16,p,1,\
c4,8,f4,8,f4,8,f4,8,e4,16,e4,8,f4,8,e4,8,d4,8,c4,8,p,1,\
g4,8,a4,8,g4,4,g4,4,f4,4,f4,4,c5,8,c4,8,c4,4,c4,4,d4,8,g4,8,e4,8,f4,16";
size_t pos=0;
while( (pos=song.find_first_of(",")) != std::string::npos)
{
float freq;
int duration;
string tone_str = song.substr(0, pos);
song = song.substr(pos+1);
string dur_str;
if((pos=song.find_first_of(",")) != std::string::npos)
{
dur_str = song.substr(0, pos);
song = song.substr(pos+1);
} else {
dur_str = song;
}
freq = theMap[tone_str];
duration = atoi(dur_str.c_str()) * 70;
if(freq > 0) Beep(freq, duration);
else Sleep(duration);
}
return 0;
}
Compiles on both Windows (mingw) and Linux g++. On Linux you need the Program "beep" installed.