ALSA project - the C library reference

/test/pcm_min.c
/*
* This extra small demo sends a random samples to your speakers.
*/
#include "../include/asoundlib.h"
static char *device = "default"; /* playback device */
unsigned char buffer[16*1024]; /* some random data */
int main(void)
{
int err;
unsigned int i;
snd_pcm_t *handle;
snd_pcm_sframes_t frames;
for (i = 0; i < sizeof(buffer); i++)
buffer[i] = random() & 0xff;
if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
if ((err = snd_pcm_set_params(handle,
SND_PCM_FORMAT_U8,
SND_PCM_ACCESS_RW_INTERLEAVED,
1,
48000,
1,
500000)) < 0) { /* 0.5sec */
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
for (i = 0; i < 16; i++) {
frames = snd_pcm_writei(handle, buffer, sizeof(buffer));
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);
}
/* pass the remaining samples, otherwise they're dropped in close */
err = snd_pcm_drain(handle);
if (err < 0)
printf("snd_pcm_drain failed: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return 0;
}
snd_strerror
const char * snd_strerror(int errnum)
Returns the message for an error code.
Definition: error.c:51
snd_pcm_close
int snd_pcm_close(snd_pcm_t *pcm)
close PCM handle
Definition: pcm.c:766
snd_pcm_recover
int snd_pcm_recover(snd_pcm_t *pcm, int err, int silent)
Recover the stream state from an error or suspend.
Definition: pcm.c:8557
snd_pcm_set_params
int snd_pcm_set_params(snd_pcm_t *pcm, snd_pcm_format_t format, snd_pcm_access_t access, unsigned int channels, unsigned int rate, int soft_resample, unsigned int latency)
Set the hardware and software parameters in a simple way.
Definition: pcm.c:8605
snd_pcm_drain
int snd_pcm_drain(snd_pcm_t *pcm)
Stop a PCM preserving pending frames.
Definition: pcm.c:1345
snd_pcm_sframes_t
long snd_pcm_sframes_t
Definition: pcm.h:390
snd_pcm_open
int snd_pcm_open(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode)
Opens a PCM.
Definition: pcm.c:2688
snd_pcm_t
struct _snd_pcm snd_pcm_t
Definition: pcm.h:408
snd_pcm_writei
snd_pcm_sframes_t snd_pcm_writei(snd_pcm_t *pcm, const void *buffer, snd_pcm_uframes_t size)
Write interleaved frames to a PCM.
Definition: pcm.c:1556
SND_PCM_ACCESS_RW_INTERLEAVED
@ SND_PCM_ACCESS_RW_INTERLEAVED
Definition: pcm.h:118
SND_PCM_FORMAT_U8
@ SND_PCM_FORMAT_U8
Definition: pcm.h:131
SND_PCM_STREAM_PLAYBACK
@ SND_PCM_STREAM_PLAYBACK
Definition: pcm.h:103