Playing sound using OpenAL
Join the DZone community and get the full member experience.Join For Free
For sound I use OpenAL, it’s free, cross-platform, I’ve managed to get it working on iPhone, Windows and Mac.
Setting up OpenAL to play a sound is pretty straight forward, a bit
First you need to create a context.
device = alcOpenDevice(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
if (device == NULL)
// Handle Exception
//Create a context
//Set active context
// Clear Error Code
Now for the second part, loading a wav file. You have to open a file, fill buffers with data and then attach it to a source.
char* alBuffer; //data for the buffer
ALenum alFormatBuffer; //buffer format
ALsizei alFreqBuffer; //frequency
long alBufferLen; //bit depth
ALboolean alLoop; //loop
unsigned int alSource; //source
unsigned int alSampleSet;
//load the wave file
alutLoadWAVFile("my_music.wav",&alFormatBuffer, (void **) &alBuffer,(unsigned int *)&alBufferLen, &alFreqBuffer, &alLoop);
//create a source
//put the data into our sampleset buffer
alBufferData(alSampleSet, alFormatBuffer, alBuffer, alBufferLen, alFreqBuffer);
//assign the buffer to this source
alSourcei(alSource, AL_BUFFER, alSampleSet);
//release the data
alutUnloadWAV(alFormatBuffer, alBuffer, alBufferLen, alFreqBuffer);
Once the sound is loaded we can play it. To do this we use alSourcePlay.
Once you’ve finished don’t forget to clean memory and release OpenAL context and device
//delete our buffer
//Get device for active context
Easy right? I’ve extended this to play the open format OGG for my engine, which is pretty cool. Since you can keep putting data to buffers you can stream a whole OGG or WAV file without loading everything into memory.
Published at DZone with permission of David Amador, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.