~kline/geiger

ref: 39894bd78e794b3e8b10d79f46c0ca679c164d51 geiger/geiger.c -rw-r--r-- 2.2 KiB
39894bd7Gareth Pulham Initial commit driven by stdin 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#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;
}