c - Alsa lib 32 位
问题描述
我一直在尝试使用 ALSA 库,但我不明白我应该如何使用它。
我采用了一个示例程序,并尝试将其修改为使用float
(32 位)而不是( 8 位unsigned char
)。但是现在当我运行它时,我在第二个循环中有一个分段错误。
这是我的代码:
#include <alsa/asoundlib.h>
snd_pcm_t *create_pcm(const char* name, snd_pcm_stream_t mode, snd_pcm_format_t format, snd_pcm_access_t access, unsigned int nbChannel, unsigned int rate, int softSample, unsigned int latency)
{
int err;
snd_pcm_t *handle;
if ((err = snd_pcm_open(&handle, name, mode, 0)) < 0) {
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
if ((err = snd_pcm_set_params(handle,
format,
access,
nbChannel,
rate,
softSample,
latency)) < 0) { /* 0.5sec */
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
return handle;
}
int main(void)
{
unsigned int i;
snd_pcm_t *handle;
snd_pcm_sframes_t frames;
float buffer[16*1024]; /* some random data */
handle = create_pcm("default", // name of the device used by the sound card
SND_PCM_STREAM_PLAYBACK, // to use the device in output
SND_PCM_FORMAT_FLOAT, // use the device with 32bit depth (float)
SND_PCM_ACCESS_RW_INTERLEAVED,
1, // use 1 channel
48000, // use 48000 Hz (dvd quality)
1, // soft resample ON
500000); // 0.5s of latency
// building random data
for(i = 0; i < sizeof(buffer); i++)
buffer[i] = i % 255; // random();
for (i = 0; i < 16; i++) {
frames = snd_pcm_writei(handle, buffer, sizeof(buffer)); // segmentation fault
if(frames < 0)
frames = snd_pcm_recover(handle, frames, 0);
if (frames < 0) {
printf("snd_pcm_writei failed: %s\n", snd_strerror(frames));
break;
}
if (frames > 0 && frames < (long)sizeof(buffer))
printf("Short write (expected %li, wrote %li)\n", (long)sizeof(buffer), frames);
}
snd_pcm_close(handle);
return 0;
}
如何使用这个 32 位的库?
我已经尝试过这种格式以及其他格式,例如小端或大端。唯一不会崩溃的格式是,SND_PCM_FORMAT_FLOAT
但它会出错:
ALSA lib pcm.c:8507:(snd_pcm_set_params) Sample format not available for PLAYBACK: Invalid argument
Playback open error: Invalid argument
提前致谢。
PS:Linux,Ubuntu 19.10 64bits
解决方案
当您写入时,可能已经发生分段错误buffer
:
for(i = 0; i < sizeof(buffer); i++)
buffer[i] = i % 255; // random();
sizeof(buffer)
会给你以字节为单位的大小而不是元素的数量。它们仅对char
(and unsigned char
) 相等,因为sizeof(char)
is 1
。您很可能想要遍历元素:
for(i = 0; i < sizeof buffer/sizeof *buffer; i++)
buffer[i] = i % 255; // random();
推荐阅读
- html - 从 R markdown 将错误上传到 Rpubs rawToChar(response$headers) 中的错误:参数“x”必须是原始向量
- python - 通过 CMD 安装软件包时出错
- php - 为什么我不能更新数据?
- kubernetes - 如何使用命令在 helm 3 中显示特定版本并安装特定版本的图表
- amazon-s3 - AWS lambda 触发 s3 对象推送但文件不存在
- node.js - Loopback 4 中间件未注册
- azure - 当范围不是 Azure AD 中的 Graph API 时,如何添加自定义声明并检索其作为 access_token 的一部分?
- java - 如何解析数组不是逗号分隔的 JSON 字符串?(Gson,Android 工作室)
- javascript - 如何将焦点设置到验证器函数内部验证失败的控件?
- node.js - 使用 Mongoose 进行虚拟填充