add beep-ao.c
[rofl0r-df-peek.git] / beep.c
blob462872267473b6f64df7b0e823c21f6709c7944b
1 #include <stdio.h>
2 #include <math.h>
4 #include <AL/al.h>
5 #include <AL/alc.h>
6 //RcB: LINK "-lopenal"
8 #include <errno.h>
9 #include <time.h>
10 int msleep(long millisecs) {
11 struct timespec req, rem;
12 req.tv_sec = millisecs / 1000;
13 req.tv_nsec = (millisecs % 1000) * 1000 * 1000;
14 int ret;
15 while((ret = nanosleep(&req, &rem)) == -1 && errno == EINTR) req = rem;
16 return ret;
19 int main() {
21 ALuint buffer;
22 ALuint source;
23 ALCdevice* device;
24 ALCcontext* context;
25 int numsamples = 1000;
26 int samplerate = 11025;
27 unsigned char samples[numsamples];
28 int i;
29 for(i = 0; i < numsamples; i++) {
30 samples[i] = round(120*sin(i*(2*M_PI)/30.0)+128);
32 device = alcOpenDevice(NULL);
33 context = alcCreateContext(device, NULL);
34 alcMakeContextCurrent(context);
36 alGenBuffers(1, &buffer);
37 alBufferData(buffer, AL_FORMAT_MONO8, samples, numsamples, samplerate);
38 if (alGetError()) return 1;
40 alGenSources(1, &source);
42 alSourcef(source, AL_PITCH, 1.0);
43 alSourcef(source, AL_GAIN, 1.0);
44 alSourcei(source, AL_BUFFER, buffer);
45 alSourcei(source, AL_LOOPING, AL_FALSE);
46 alSourcei(source, AL_BUFFER, buffer);
47 if (alGetError()) return 1;
49 alSourcePlay(source);
50 if (alGetError()) return 1;
52 float delay = ((float)numsamples/(float)samplerate) * 1000.f;
54 msleep(((long)(delay))*2);
55 ALint state;
56 do {
57 msleep(1);
58 alGetSourcei(source, AL_SOURCE_STATE, &state);
59 } while(alGetError()==AL_NO_ERROR && state==AL_PLAYING);
61 alSourceStop(source);
63 alDeleteSources(1, &source);
64 alDeleteBuffers(1, &buffer);
66 alcMakeContextCurrent(NULL);
68 alcDestroyContext(context);
69 alcCloseDevice(device);
71 return 0;