I have a std::queue of sounds to play (in OpenAL) and I need to know how to block my threaded function so that I don't end up playing all of the sounds in the queue at the same time.
I want to block at line 38 until the sound is done playing. Any pointers? (Pun intended).
#include <queue>
#inlcude <boost/thread>
#include <al/al.h>
#include <al/alc.h>
#include "cSoundObject.h"
void PopulateSndBuf(std::queue<cSoundObject> &SNDBUF);
void play_sounds (std::queue<cSoundObject> &SNDBUF);
int main()
{
std::queue<cSoundObject> SNDBUF;
while(true)
{
PopulateSndBuf(SNDBUF); // Might add something to the sound buffer.
staticbool playing = false;
if (!SNDBUF.empty() && !playing) // Only call this function if SNDBUF is not empty and not playing
{
playing = true;
boost::thread sndthrd(play_sounds,boost::ref(SNDBUF));
}
if (SNDBUF.empty()) playing = false;
Sleep(16); // Runs according to a real-time scheduler, not really this
}
}
void play_sounds(std::queue<cSoundIF> &SNDBUF)
{
while(!SNDBUF.empty())
{
ALuint source = SNDBUF.front()->ALsource());
alSourcePlay(source); // Starts playing the sound
// WAIT UNTIL SOUND IS DONE PLAYING
SNDBUF.pop();
}
}
I know the length of the WAVE files so I could just do something like:
1 2 3 4 5
double timer = 0.;
while(timer < SNDBUF.front().length())
{
timer += dTime; // dTime would increment based on a timer.
}
But this has two problems:
1) It'll eat up all available processor time.
2) A signal from OpenAL would have less chance of deviating from what we are actually hearing.
I thought I was creating only one thread by using bool playing to prevent creating a new one until the sound buffer was empty. Are you saying there is a simpler way of doing this?
Regardless, I think my base question still stands..
You probably should create the thread at the start of the program, then just add items to the queue while play_sounds just plays the next item from the queue.
That would leave me with this. Wouldn't this make the thread take all remaining processing time? Also, I am still not sure how to tell if the sound is complete so that I should pop the last one and play the next.
Thanks. Still learning about threading, I'll look up mutex's.
The main application doesn't actually use a sleep command, this is part of a dll where the "main" function is called by a real-time process at a rate of 60Hz. I'll figure it out.