Play RAW pcm Audio using ALSA API

  alsa, c++, playback

I have a buffer of length 1024 coming over the network filled with single channel audio data at 48000Hz in S32LE format. I’m able to play this back using SDL2 however I need change this to use the ALSA API. I’ve followed countless tutorials but all I’m getting is static.

This is the setup code

    if ((err = snd_pcm_open(&pcm_handle, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0)
    {
        printf("ERROR: Failed to open device: %sn", snd_strerror(err));
        exit(EXIT_FAILURE);
    }

    if ((err = snd_pcm_set_params(pcm_handle, SND_PCM_FORMAT_S32_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 1, 48000, 0, 0)) < 0)
    {
        printf("ERROR: Failed to set device params: %sn", snd_strerror(err));
        exit(EXIT_FAILURE);
    }

This is the output code.

while (running)
    {
        auto p = client->getPacket();

        snd_pcm_sframes_t frames = snd_pcm_writei(pcm_handle, p->data, 512);
        if (frames < 0)
            frames = snd_pcm_recover(pcm_handle, frames, 0);
        if (frames < 0)
        {
            printf("snd_pcm_writei failed: %sn", snd_strerror(err));
            break;
        }
    }

I think my part of issue is my understanding of how the Period, Frames and Samples are related. I know writei takes the size in frames but how does that translate to the length of data in the buffer and then how does the period fit into everything

Source: Windows Questions C++

LEAVE A COMMENT