C program for playing sound

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello, I am trying to learn how to use the ALSA API library, I have the following program to play a stereo 16 bit wav file at 11025 Hz. I have created a buffer with 256 frames with 2 periods (period size 128 frames), but it only outputs a single tick and the program ends. Appreciate any help.

Here is the sound file: http://mauvecloud.net/sounds/pcm1611s.wav

And here is the program:

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

#define STEREO 2
#define BITS 16 / 8
#define FRAMEBUFFERSIZE 512 // in samples
#define PERIODS 2
#define SAMPLERATE 11025

int main(void)
{
    snd_pcm_t *handle;
    uint32_t channels = STEREO;
    uint32_t sample_size = BITS; // 16 bit
    uint32_t frame_size = sample_size * channels;
    snd_pcm_uframes_t frames = FRAMEBUFFERSIZE;
    snd_pcm_uframes_t frames_per_period = frames / PERIODS;
    int dir = 0; // No idea what this does.
    snd_pcm_hw_params_t *params;
    signed short framebuffer[FRAMEBUFFERSIZE * STEREO * BITS] = {0};
    FILE *wav;
    int size;

snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0); // SND_PCM_NONBLOCK);
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(handle, params);
    snd_pcm_hw_params_set_buffer_size(handle, params, frames);
snd_pcm_hw_params_set_period_size(handle, params, frames_per_period, dir);
    snd_pcm_hw_params_set_rate(handle, params, SAMPLERATE, dir);
snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
    snd_pcm_hw_params_set_channels(handle, params, STEREO);
    snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);
    snd_pcm_hw_params(handle, params);

    // Insert samples to framebuffer.
    wav = fopen("pcm1611s.wav", "r");
    fseek(wav, 0L, SEEK_END);
    size = ftell(wav);
    fseek(wav, 0L, SEEK_SET);
    size /= sizeof(signed short);
    while (size > 0)
    {
fread(framebuffer, sizeof(signed short), FRAMEBUFFERSIZE * STEREO * BITS, wav);
        snd_pcm_writei(handle, framebuffer, frames);
        size -= FRAMEBUFFERSIZE * STEREO * BITS;
    }
    snd_pcm_drain(handle);
    snd_pcm_close(handle);
    exit(EXIT_SUCCESS);
}


_______________________________________________
Alsa-user mailing list
Alsa-user@xxxxxxxxxxxxxxxxxxxxx
https://lists.sourceforge.net/lists/listinfo/alsa-user



[Index of Archives]     [ALSA Devel]     [Linux Audio Users]     [Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [Yosemite Photos]     [KDE Users]     [Fedora Tools]

  Powered by Linux