Created
October 26, 2012 20:37
-
-
Save velikodniy/3961359 to your computer and use it in GitHub Desktop.
Beeper (libao)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -lao -o beep beep.cpp | |
#include <ao/ao.h> | |
#include <cmath> | |
#include <cstdlib> | |
#define BITS 16 | |
#define CHANNELS 1 | |
#define RATE 22050 | |
class Beeper { | |
ao_device *device; | |
int driver; | |
ao_sample_format format; | |
public: | |
Beeper() { | |
ao_initialize(); | |
this->driver = ao_default_driver_id(); | |
this->format.bits = BITS; | |
this->format.channels = CHANNELS; | |
this->format.rate = RATE; | |
this->format.byte_format = AO_FMT_LITTLE; | |
this->device = ao_open_live(driver, &format, NULL); | |
if (this->device == NULL) | |
exit(1); | |
} | |
void operator() (double freq, double time, double volume = 0.75) { | |
int buf_size = static_cast<int>(this->format.bits/8 * this->format.channels * this->format.rate * time); | |
char *buffer = new char[buf_size]; | |
int sample; | |
for (int i = 0; i < this->format.rate * time; i++) { | |
for (int c = 0; c < this->format.channels; c++) { | |
sample = (int)(volume * (1<<(this->format.bits - 1)) * sin(2 * M_PI * freq * ((float) i/format.rate))); | |
for (int j = 0; j < this->format.bits/8; j++) { | |
buffer[this->format.bits/8*i*this->format.channels + this->format.channels*c + j] = sample & 0xff; | |
sample >>= 8; | |
} | |
} | |
} | |
ao_play(device, buffer, buf_size); | |
delete[] buffer; | |
} | |
~Beeper() { | |
ao_close(device); | |
ao_shutdown(); | |
} | |
}; | |
int main(int argc, char **argv) | |
{ | |
Beeper b; | |
int count = (argc == 1) ? 20 : atoi(argv[1]); | |
for (int i=0; i < count; i++){ | |
b(880.0, 0.3); | |
b(0.0, 0.2); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment