.
[rofl0r-df-peek.git] / beep.c
blob2f42ab83f47ff55fc200bcdd577914d08ef9183a
1 #include <stdio.h>
2 #include <math.h>
4 #include <AL/al.h>
5 #include <AL/alc.h>
7 #include <errno.h>
8 #include <time.h>
9 int msleep(long millisecs) {
10 struct timespec req, rem;
11 req.tv_sec = millisecs / 1000;
12 req.tv_nsec = (millisecs % 1000) * 1000 * 1000;
13 int ret;
14 while((ret = nanosleep(&req, &rem)) == -1 && errno == EINTR) req = rem;
15 return ret;
18 int main() {
20 ALuint buffer;
21 ALuint source;
22 ALCdevice* device;
23 ALCcontext* context;
24 int numsamples = 1000;
25 int samplerate = 11025;
26 unsigned char samples[numsamples];
27 int i;
28 for(i = 0; i < numsamples; i++) {
29 samples[i] = round(120*sin(i*(2*M_PI)/30.0)+128);
31 device = alcOpenDevice(NULL);
32 context = alcCreateContext(device, NULL);
33 alcMakeContextCurrent(context);
35 alGenBuffers(1, &buffer);
36 alBufferData(buffer, AL_FORMAT_MONO8, samples, numsamples, samplerate);
37 if (alGetError()) return 1;
39 alGenSources(1, &source);
41 alSourcef(source, AL_PITCH, 1.0);
42 alSourcef(source, AL_GAIN, 1.0);
43 alSourcei(source, AL_BUFFER, buffer);
44 alSourcei(source, AL_LOOPING, AL_FALSE);
45 alSourcei(source, AL_BUFFER, buffer);
46 if (alGetError()) return 1;
48 alSourcePlay(source);
49 if (alGetError()) return 1;
51 float delay = ((float)numsamples/(float)samplerate) * 1000.f;
53 msleep(((long)(delay))*2);
54 ALint state;
55 do {
56 msleep(1);
57 alGetSourcei(source, AL_SOURCE_STATE, &state);
58 } while(alGetError()==AL_NO_ERROR && state==AL_PLAYING);
60 alSourceStop(source);
62 alDeleteSources(1, &source);
63 alDeleteBuffers(1, &buffer);
65 alcMakeContextCurrent(NULL);
67 alcDestroyContext(context);
68 alcCloseDevice(device);
70 return 0;