gpt4 book ai didi

c - ALSA 'snd_pcm_writei' 阻塞模式下的行为

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:23 37 4
gpt4 key购买 nike

我稍微修改了取自 ALSA Project website 的演示为了在我笔记本电脑的声卡(Intel PCH ALC3227 Analog,Ubuntu 18.04)上进行测试,它需要 2 个 channel 和 16 位整数。我还将延迟加倍(1 秒),关闭重采样并使演示持续时间更长。这是代码(为了综合起见,未粘贴运行时错误检查)

#include <alsa/asoundlib.h>
#include <stdlib.h>

static char *device = "hw:1,0"; /* playback device */
snd_output_t *output = NULL;
unsigned char buffer[16*1024]; /* some random data */
int main(void) {
int err;
unsigned int i;
snd_pcm_t *handle;
snd_pcm_sframes_t frames;
for (i = 0; i < sizeof(buffer); i++)
buffer[i] = (unsigned char) (rand() & 0xff);
snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)
snd_pcm_set_params(handle, SND_PCM_FORMAT_S16_LE,
SND_PCM_ACCESS_RW_INTERLEAVED, 2, 48000, 0, 1E6);
// Print actual buffer size
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_malloc(&hw_params);
snd_pcm_hw_params_current(handle, hw_params);
snd_pcm_uframes_t bufferSize;
snd_pcm_hw_params_get_buffer_size(hw_params, &bufferSize);
printf("ALSA buffer size = %li\n", bufferSize);
// playback
for (i = 0; i < 256; ++i) {
frames = snd_pcm_writei(handle, buffer, sizeof(buffer) / 4);
if (frames < 0)
frames = snd_pcm_recover(handle, (int) frames, 0);
if (frames < 0) {
printf("snd_pcm_writei failed: %s\n", snd_strerror((int) frames));
break;
}
if (frames > 0 && frames < (long) sizeof(buffer) / 4)
printf("Short write (expected %li, wrote %li)\n",
(long) sizeof(buffer) / 4, frames);
}
snd_pcm_hw_params_free(hw_params);
snd_pcm_close(handle);
return (0);
}

音频有效,但有人能解释一下为什么我有时会得到如下输出

ALSA buffer size = 16384
Short write (expected 4096, wrote 9)
Short write (expected 4096, wrote 4080)

表示 snd_pcm_writei 写入的帧数少于预期?根据ALSA docs ,我知道必须出现一个信号,但我不明白原因和哪个信号。

我也尝试将 buffer 的大小减半,但结果是一样的。

最佳答案

报错时报short read,但部分帧已经写入成功。

你应该用剩余的缓冲区再次调用同一个函数;如果错误不是暂时性的,则将被报告。(这个示例代码是错误的;它只是忽略了缓冲区的剩余部分没有被写入。)

关于c - ALSA 'snd_pcm_writei' 阻塞模式下的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55182162/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com