我正在阅读ALSA教程,并提出了有关捕获PCM数据的问题。我编写了以下示例(类似于本教程中的示例)。就是这里(省略错误检查和打印消息):
#include <alsa/asoundlib.h>
int rate = 44100;
int periods = 2;
snd_pcm_uframes_t period_size = 8192;
int exact_rate;
int direction;
int main(int argc, char ** argv){
snd_pcm_t *pcm_handle;
snd_pcm_stream_t stream = SND_PCM_STREAM_CAPTURE; // <--- for capturin PCM data
snd_pcm_hw_params_t *hwparams;
snd_pcm_hw_params_alloca(&hwparams);
snd_pcm_open(&pcm_handle, pcm_name, stream, 0)
snd_pcm_hw_params_any(pcm_handle, hwparams)
snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
snd_pcm_hw_params_set_format(pcm_handle, hwparams, SND_PCM_FORMAT_S16_LE);
snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &exact_rate, &direction);
snd_pcm_hw_params_set_channels(pcm_handle, hwparams, 2);
snd_pcm_hw_params_set_periods(pcm_handle, hwparams, periods, direction);
snd_pcm_hw_params_set_buffer_size(pcm_handle, hwparams, (period_size * periods) >> 2);
snd_pcm_hw_params(pcm_handle, hwparams);
//reading PCM data, microphone is not plugged
char *buffer = calloc(sizeof(char), period_size * periods);
int pcm_read_return = 0;
pcm_read_return = snd_pcm_readi(pcm_handle, buffer, period_size >> 2);
printf("Read %d frames\n", pcm_read_return); //always 2048
printf("Buffer: %s\n", buffer); //Some data,not all bytes are 0
free(buffer);
return 0;
}
我不太了解这种行为。始终读取的帧数为2048
。 它们始终为0 有时会产生一些非零字节。我预计不会读取任何帧,因为拔出了麦克风并且应该没有PCM数据。