I want to play audio while a game is running (and also inside when the game is running)
is this a good way to play a sound in openal?
is opening new threads the best way to do this? (would this cause lag if there are too many threads running at once?)
CODE for a simple audio function (threaded):
#include <iostream>
#include <thread>
#include <AL/alut.h>
#include <sndfile.h>
//using namespace std;
void playSound(const std::string &file)
{
alutInit(NULL, NULL);
ALuint buffer, source;
SNDFILE* sndfile;
SF_INFO sndinfo;
sndfile = sf_open(file.c_str(), SFM_READ, &sndinfo);
int samples = sndinfo.channels * sndinfo.frames;
int format = (sndinfo.channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
short* bufferData = new short[samples];
sf_read_short(sndfile, bufferData, samples);
sf_close(sndfile);
alGenBuffers(1, &buffer);
alBufferData(buffer, format, bufferData, samples * sizeof(short), sndinfo.samplerate);
delete[] bufferData;
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
alSourcePlay(source);
ALint state;
do {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
alGetSourcei(source, AL_SOURCE_STATE, &state);
} while (state != AL_STOPPED);
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
alutExit();
}
void playsound(std::string file)
{
std::thread sound(playSound, file);
sound.detach();
}
int main()
{
playsound("test.wav");
while (true)
{
//the game code would go here ...
}
alutExit();
return 0;
}