gpt4 book ai didi

c - Alsa 库 32 位

转载 作者:行者123 更新时间:2023-11-30 14:33:15 26 4
gpt4 key购买 nike

我尝试使用 ALSA 库有一段时间了,但我不明白应该如何使用它。

我拿了一个示例程序,并尝试修改它以使用float(32位)而不是unsigned char(8位)。但现在当我运行它时,我在第二个循环中出现段错误。

这是我的代码:

#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

提前致谢。

附:Linux、Ubuntu 19.10 64 位

最佳答案

当您写入buffer时,段错误可能已经发生:

for(i = 0; i < sizeof(buffer); i++)
buffer[i] = i % 255; // random();

sizeof(buffer) 将为您提供以字节为单位的大小,而不是元素的数量。它们仅对于 char(和 unsigned char)而言相等,因为 sizeof(char)1。您很可能想要迭代元素:

for(i = 0; i < sizeof buffer/sizeof *buffer; i++)
buffer[i] = i % 255; // random();

关于c - Alsa 库 32 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59446047/

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