Hi Toradex Community,
I’ve been following the article to play sounds via ALSA in C++: How to play audio on TorizonCore using Alsa and C/C++ | Toradex Developer Center
Using the code as is works well. The article points to the following code: torizon-samples/alsa-example.cpp at bullseye · toradex/torizon-samples · GitHub
However, in my case, I would also like to implement a Stop Audio feature, since my application will sometimes require a sound interruption. For example, while a background sound is playing, I may output an error popup + sound, so I’d want to interrupt the background sound as it’s playing.
Using the code as is does not allow to implement such interruption since snd_pcm_writei()
is in blocking mode.
I tried to modify the code, primarily by setting the flag SND_PCM_NONBLOCK
when opening my PCM device.
So in line 314 of the example, I replaced:
if ((err = snd_pcm_open(&PlaybackHandle, &SoundCardPortName[0], SND_PCM_STREAM_PLAYBACK, 0)) < 0)
with
if ((err = snd_pcm_open(&PlaybackHandle, &SoundCardPortName[0], SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)) < 0)
The code is now able to continue after calling snd_pcm_writei()
. I plan on implementing the interruption by doing something like this right after since I’m separating this module in a different thread:
while(snd_pcm_state(PlaybackHandle) == SND_PCM_STATE_RUNNING)
{
mutex.lock();
if(abortFlag){
qDebug() << "Dropping PCM" << Qt::endl;
snd_pcm_drop(PlaybackHandle);
break;
}
mutex.unlock();
}
However, in Non-Blocking mode, Line 256 of the code example frames = snd_pcm_writei(PlaybackHandle, WavePtr + count, WaveSize - count);
returns a crazy value: 4294967285. It’s oddly close to the max unsigned int32 value (4294967295).
The sound starts playing for like half a second and stops when this value outputs, resulting in the PCM state to skip SND_PCM_STATE_RUNNING
and jump to SND_PCM_STATE_XRUN
right away.
I’d like to know if someone else has tried implementing a stop sound feature with this example code, or if someone can identify why the audio doesn’t work in Non-Blocking Mode only? Is this the right approach?
Thanks in advance,
Anthony