#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>
char stop = 0;
char decay = 0;
void* worker(void *z){
// mostly lifted from https://www.alsa-project.org/alsa-doc/alsa-lib/_2test_2pcm__min_8c-example.html
static char *device = "default";
unsigned char click[16];
unsigned char blank[16];
int err;
unsigned int i;
snd_pcm_t *handle;
snd_pcm_sframes_t frames;
for (i = 0; i < sizeof(click); i++){
click[i] = 0;
blank[i] = 0;
}
click[0] = 250;
if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
fprintf(stderr, "Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
if ((err = snd_pcm_set_params(handle,
SND_PCM_FORMAT_U8,
SND_PCM_ACCESS_RW_INTERLEAVED,
1,
8000,
1,
125)) < 0) {
fprintf(stderr, "Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
while (!stop) {
if (decay) {
frames = snd_pcm_writei(handle, click, sizeof(click));
decay = 0;
}
else
frames = snd_pcm_writei(handle, blank, sizeof(click));
if (frames < 0)
frames = snd_pcm_recover(handle, frames, 0);
if (frames < 0) {
fprintf(stderr, "snd_pcm_writei failed: %s\n", snd_strerror(err));
break;
}
if (frames > 0 && frames < (long)sizeof(click))
fprintf(stderr, "Short write (expected %li, wrote %li)\n", (long)sizeof(click), frames);
}
snd_pcm_close(handle);
return 0;
}
int main(){
pthread_t worker_thread;
int rc = pthread_create(&worker_thread, NULL, worker, (void *)NULL);
if (rc) {
fprintf(stderr, "Whoops!\n");
return -1;
}
for (;;){
char input = getchar();
if (input != 10){
break;
}
decay = 1;
}
stop = 1;
fprintf(stderr, "Stopping: %d\n", stop);
pthread_join(worker_thread, NULL);
return 0;
}