首页 > 解决方案 > 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

标签: clinuxaudioalsa

解决方案


当您写入时,可能已经发生分段错误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();

推荐阅读