Skip to content

Instantly share code, notes, and snippets.

@alepez
Last active May 29, 2017 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alepez/373f366633ef4f87ce16485539af9f14 to your computer and use it in GitHub Desktop.
Save alepez/373f366633ef4f87ce16485539af9f14 to your computer and use it in GitHub Desktop.
openal beep
#include <cmath>
#include <iostream>
#include <thread>
using namespace std;
#include <AL/alut.h> // OpenAl
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 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] = 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();
for(int i = 1; i < 1000; i++)
{
thread t(Beep, 440,0.5);
t.detach();
alutSleep(0.01);
cout<< i << "\n";
}
exit_al();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment