linux – ALSA audio read function 2x too slow
I’m writing an ALSA audio rendering implementation and fairly literally copied the code from an example.
However, for some reason and despite all logging to the contrary, the audio I’m getting out is playing at exactly half the speed and pitch. (I’ve tried this with several different input files like sine waves and speech.)
All of that seems to point at the sample rate being half or something, but that doesn’t seem to be the case. I am timing the snd_pcm_writei
call (in “blocking” mode), and can see it takes exactly double the time I think a frame should take. Timing code:
auto startTime = std::chrono::high_resolution_clock::now();
const snd_pcm_sframes_t nFramesWritten = snd_pcm_writei(m_pSoundDevice, pRenderData, nFramesToWrite);
// Calculate the elapsed time
auto endTime = std::chrono::high_resolution_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
printf("Elapsed time: %lu ms", elapsedTime.count());
If for example I run at 48000Hz with a block size of 512, the ALSA setup log tells me:
Sound device format:
stream : PLAYBACK
access : RW_INTERLEAVED
format : S24_LE
subformat : STD
channels : 2
rate : 48000
exact rate : 48000 (48000/1)
msbits : 32
buffer_size : 2048
period_size : 512
period_time : 10666 <--- This is the relevant number, i.e. 10.666 milliseconds (512 / 48000)
tstamp_mode : NONE
However, the timing code gives me:
Rendering 512 frames
Elapsed time: 21 ms
Rendering 512 frames
Elapsed time: 21 ms
Rendering 512 frames
Elapsed time: 20 ms
etc...
With whatever frame size I chose, this keeps happening, and the sound I’m getting out is slow and downpitched by 2x. Also different sample types (Int16, Int24, Int32, Float) all report the same issue. What’s going on here?
Read more here: Source link