ALSA: Ways to prevent underrun for speaker
I assume this code runs in a tight loop and is intended to block on snd_pcm_writen()
. The sample-rate isn't given; I assume 48kHz since the numbers all divide nicely.
What I think is going here is as follows:
snd_pcm_write()
doesn't guarantee to write all frames provided (the return value is only ever checked for error conditions). Judging from the logging ofsnd_pcm_avail()
it's in fact consumingavail_min
or144
frames on each. This is 3ms of audio.- Assuming that audio is not running at this point, after two writes, the number of frames in the buffer is equal to
start_threshold
- at288
samples; audio output starts - calls to
printf()
block, and I seem to remember thatsnd_pcm_avail()
has to synchronise with the audio output hardware and might also block. Since you are now 6ms ahead of the playback, it's entirely possible that the buffer is running dry during the time of the third call ofsnd_pcm_writen()
In summary, you shouldn't be calling printf()
at this point, and you probably need to compensate for fact that snd_pcm_writen()
isn't consuming all of the frames in pSpeakerBuf