文章目录
1 ALSA概览图
2 流传输时的ALSA栈
2.1 一个最小的录音程序和一个最小的播放程序
为方便说明,让我们用tinyalsalib写一个最简单的录音程序来录5秒的音频(PCM数据)并输出到stdout,然后写一个最简单的音频播放程序来播放来自stdin的PCM数据。
— sample1.c —
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyalsa/asoundlib.h>
int main(void)
{
unsigned int card = 0;
unsigned int device = 0;
struct pcm *pcm = NULL;
struct pcm_config config;
unsigned int size = 0;
char *buffer = NULL;
int duration_secs = 5;
int n = 0;
memset(&config, 0, sizeof(config));
config.channels = 2;
config.rate = 48000;
config.period_size = 1024;
config.period_count = 4;
config.format = PCM_FORMAT_S16_LE;
pcm = pcm_open(card, device, PCM_IN, &config);
if (!pcm || !pcm_is_ready(pcm)) {
fprintf(stderr, "Unable to open PCM device (%s)\n", pcm_get_error(pcm));
goto err;
}
size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
buffer = malloc(size);
if (!buffer) {
fprintf(stderr, "Unable to allocate %u bytes\n", size);
goto err;
}
n = pcm_frames_to_bytes(pcm, duration_secs * config.rate) / size;
while (n-- && !pcm_read(pcm, buffer, size)) {
fwrite(buffer, 1, size, stdout);
}
err:
free(buffer);
pcm_close(pcm);
return 0;
}
编译:
gcc sample1.c -ltinyalsa -ldl
运行:
./a.out > test.pcm
录到的声音被保存成test.pcm
文件。
现在让我们写一个最简单的程序去播放这个文件。
— sample2.c —
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include