8 #include <linux/soundcard.h>
9 #include <alsa/asoundlib.h>
10 #include "linux_audio.h"
12 snd_pcm_t *get_dsp_handle(int sample_rate)
16 snd_pcm_hw_params_t *hw_params;
18 if ((err = snd_pcm_open(&handle, "plughw:0,0", SND_PCM_STREAM_CAPTURE, 0)) < 0) {
19 fprintf(stderr, "cannot open audio device plughw:0,0: %s\n",
24 if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0) {
25 fprintf(stderr, "cannot allocate hardware parameter structure: %s\n",
30 if ((err = snd_pcm_hw_params_any(handle, hw_params)) < 0) {
31 fprintf(stderr, "cannot initialize hardware parameter structure: %s\n",
36 if ((err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
37 fprintf(stderr, "cannot set access type: %s\n",
42 if ((err = snd_pcm_hw_params_set_format(handle, hw_params, SND_PCM_FORMAT_S16_LE)) < 0) { // FIXME
43 fprintf(stderr, "cannot set sample format: %s\n",
48 if ((err = snd_pcm_hw_params_set_rate(handle, hw_params, sample_rate, 0)) < 0) {
49 fprintf(stderr, "cannot set sample rate: %s\n",
54 if ((err = snd_pcm_hw_params_set_channels(handle, hw_params, 1)) < 0) {
55 fprintf(stderr, "cannot set channel count: %s\n",
60 if ((err = snd_pcm_hw_params(handle, hw_params)) < 0) {
61 fprintf(stderr, "cannot set parameters: %s\n",
66 snd_pcm_hw_params_free(hw_params);
68 if ((err = snd_pcm_prepare(handle)) < 0) {
69 fprintf(stderr, "cannot prepare audio interface for use: %s\n",
78 void read_chunk(snd_pcm_t *handle, short *in, unsigned num_samples)
81 int samples_left = num_samples;
83 while (samples_left > 0) {
84 ret = snd_pcm_readi(handle, in, samples_left);
90 fprintf(stderr, "ALSA underrun\n");
91 snd_pcm_prepare(handle);
95 fprintf(stderr, "snd_pcm_readi: %s\n", snd_strerror(ret));
103 // make a pure 440hz sine for testing
104 void read_chunk(snd_pcm_t *handle, short *in, unsigned num_samples)
106 static double theta = 0.0;
107 for (unsigned i = 0; i < num_samples; ++i) {
108 in[i] = 32768.0 * cos(theta);
109 theta += 2.0 * M_PI * 440.0 / double(SAMPLE_RATE);
114 void write_sine(int dsp_fd, double freq, unsigned num_samples, unsigned sample_rate)
116 static double theta = 0.0;
117 short buf[num_samples];
119 for (unsigned i = 0; i < num_samples; ++i) {
120 buf[i] = short(cos(theta) * 16384.0);
121 theta += 2.0 * M_PI * freq / double(sample_rate);
124 write(dsp_fd, buf, num_samples * sizeof(short));