Created
May 8, 2017 14:50
-
-
Save alepez/5b523324ad2cca907a8f059682f6767c to your computer and use it in GitHub Desktop.
openal beep with volume
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
#include <AL/alut.h> // OpenAl | |
#include <cmath> | |
#include <iostream> | |
#include <thread> | |
using namespace std; | |
void init_al() { | |
const char* defname = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER); | |
ALCdevice* dev = alcOpenDevice(defname); | |
ALCcontext* ctx = alcCreateContext(dev, NULL); | |
alcMakeContextCurrent(ctx); | |
} | |
void exit_al() { | |
ALCcontext* ctx = alcGetCurrentContext(); | |
ALCdevice* dev = alcGetContextsDevice(ctx); | |
alcMakeContextCurrent(0); | |
alcDestroyContext(ctx); | |
alcCloseDevice(dev); | |
} | |
void Beep(float freq = 440, float volume = 1.0, float seconds = 0.5) { | |
ALuint buf; | |
alGenBuffers(1, &buf); | |
unsigned sample_rate = 10000; | |
size_t buf_size = seconds * sample_rate; | |
short* samples = new short[buf_size]; | |
if (samples == 0) { | |
cout << "It seems there is no more heap memory. Sorry we cannot make a beep!"; | |
} | |
for (unsigned i = 0; i < buf_size; i++) | |
samples[i] = volume * 32760 * sin(2 * M_PI * i * freq / sample_rate); | |
alBufferData(buf, AL_FORMAT_MONO16, samples, buf_size, sample_rate); | |
ALuint src; | |
alGenSources(1, &src); | |
alSourcei(src, AL_BUFFER, buf); | |
alSourcePlay(src); | |
alutSleep(seconds + 0.5); | |
delete[] samples; | |
alSourceStopv(1, &src); // new line | |
alDeleteSources(1, &src); // new line | |
alDeleteBuffers(1, &buf); // new line | |
} | |
int main() { | |
init_al(); | |
Beep(440, 1.0, 0.5); | |
Beep(440, 0.8, 0.5); | |
Beep(440, 0.6, 0.5); | |
Beep(440, 0.4, 0.5); | |
Beep(540, 0.2, 0.1); | |
Beep(740, 1.0, 0.2); | |
Beep(840, 1.0, 0.3); | |
Beep(940, 1.0, 0.5); | |
exit_al(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment