/*
alsa_record.c
*/
#include <alsa/asoundlib.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
short buffer[4096];
int err;
unsigned int samplerate = 44100;
snd_pcm_t *handle;
snd_pcm_sframes_t frames;
unsigned long ptr = 0, i;
FILE *pOutFile = fopen("rec.pcm","wb+");
err = snd_pcm_open(&handle, "plughw:2,0", SND_PCM_STREAM_CAPTURE, 0);
if (err < 0) {
perror("Device open error.\n");
return -1;
}
err = snd_pcm_set_params(handle,
SND_PCM_FORMAT_S16_LE,
SND_PCM_ACCESS_RW_INTERLEAVED,
1, /* 通道数 */
samplerate , /* 采样率 */
1, /* 重采样 */
100000 /* 延迟(us) */
);
if (err < 0) {
perror("Playback open error.\n");
return -1;
}
int number = 0;
while (1) {
number++;
if(number > 100)
break;
frames = snd_pcm_readi(handle, buffer, 4096);
if (frames == -EPIPE) {
/* EPIPE means overrun */
fprintf(stderr, "overrun occurred\n");
snd_pcm_prepare(handle);
} else if (frames < 0) {
fprintf(stderr, "error from read.\n");
} else if (4096 != (int)frames) {
fprintf(stderr, "read %ld, expected 4096.\n", frames);
}
int ret = fwrite(buffer,1,sizeof(buffer),pOutFile);
printf("the ret is %d, the number is %d \n",ret,number);
}
snd_pcm_close(handle);
fclose(pOutFile);
return 0;
}