Ivan Johansen
Ivan Johansen

Reputation: 165

Retrieving ALSA playback delay

I am trying to play sound on a Raspberry Pi 3 retrieved from a library. I need to provide an accurate time for when the samples will hit the speaker. The library will then provide the samples synchronized to the time. I am using ALSA to play the sound. However I do not seem to be able to get the time accurately. I have tried several combinations of snd_pcm_htimestamp(), snd_pcm_delay(), snd_pcm_status_get_delay() and snd_pcm_status_get_audio_htstamp(). I have also tried with both writei and mmap.

Can anyone give me a hint to how I can retrieve an accurate time for when the samples will be played?

Upvotes: 1

Views: 1095

Answers (2)

Ivan Johansen
Ivan Johansen

Reputation: 165

Now I am going to answer my own question. It turns out that using snd_pcm_status() is actually the way to go. I just had a bug in my first attempt. The following code calculates the time the next sample added will be played in nanoseconds since boot:

snd_pcm_status_t *pcm_status;
snd_pcm_status_alloca(&pcm_status); //Allocate space on the stack
snd_pcm_status(handle, pcm_status);
int delay = snd_pcm_status_get_delay(pcm_status);
snd_htimestamp_t tstamp; 
snd_pcm_status_get_audio_htstamp(pcm_status, &tstamp);

uint64_t Time = tstamp.tv_sec * (uint64_t)1000000000 + tstamp.tv_nsec;  
Time += (delay * (uint64_t)1000000000) / 44100;

Upvotes: 0

CL.
CL.

Reputation: 180210

snd_pcm_*delay() gives you the best estimate. However, many drivers do not implement this, and there might be additional hardware that is not known to the software.

Upvotes: 1

Related Questions