Can someone explain how to safely stop from playing with ALSA drivers? I use snd_pcm_writei() for write into ALSA ring buffer in chunks of "period" buffer sizes, pretty much simple. After write, I found it's difficult to safely exit, in terms of need to exit after all samples are played from ring buffer (inside driver).
After playing, I found that stream is still in SND_PCM_STATE_RUNNING state (enum 3) which seems normal, since rest of ring buffer needs to be played. So I tried pooling the state
do
{
err = snd_pcm_state(handle);
}while(err==3);
printf("\nDone.\n\n"); // never gets here
Ok, there is a function for draining audio stream:
snd_pcm_drain(handle);
do
{
err = snd_pcm_state(handle);
}while(err==3);
printf("\nDone.\n\n");
This ends up with code 1 which means SND_PCM_STATE_SETUP shoudn't ne STOP or something ? But anyway, the stream isn't played until end. The only way to test is to put a
while(1);
And this ensures the whole audio is played. Any thoughts?
Thanks very much in advance,
I discovered the problem but need assistance to solve:
The function snd_pcm_writei() needs a const void* buffer and I use a dynamically allocated one:
snd_pcm_sframes_t snd_pcm_writei ( snd_pcm_t * pcm,
const void * buffer,
snd_pcm_uframes_t size
)
frames = snd_pcm_writei (handle, buff, period_size);
static short buf[240]; // this works
// this is not working
if ((buff = calloc(0,period_size)) == NULL) {
printf("No enough memory for period buffer\n");
exit(EXIT_FAILURE);
}
Any idea about how to use snd_pcm_writei() with a dynamically allocated buffer?