[Openal] Audio Library Design

Chris Robinson chris.kcat at gmail.com
Thu Sep 23 12:45:28 PDT 2010


On Thursday, September 23, 2010 11:54:20 am Eric Stock wrote:
> Hello, I have written a simple sound library for a windows video game.  I
> am providing functions for loading and playing a sound and also for
> streaming a sound.  I am supporting Ogg and Wave files.
> 
> here is an example of how the library can be used to load and play a sound:
> 
> handle =  audioManger::Instance().PlaySound(const char* p_strSound); 
> //load and play
> audioManger::Instance().SetVolume(handle, MAX_VOLUME);    //the handle can
> be used to manage the playback parameters of the sound
> 
> once the sound has finished playing, the handle becomes invalid and the
> resources associated with that sound( AL_Buffers and AL_Sources) are
> released back to the manager.
> 
> My problem is that every time I want to load and  play a sound I have to
> load it from disk.  This seems like a very poor design if I want to play a
> sound effect many times during part of my application.

The way I would do it would be to have a map of the sound name (filename or 
higher level string/id) and the AL buffer. When you go to play a sound, you 
check if the corresponding buffer already exists in the map, and if so, just 
take the AL buffer, otherwise load it and store it in the AL buffer, and place 
it in the map. So essentially (C++ example):

std::map<std::string,ALuint> BufferMap;

SoundHandle *PlaySound(const char *name)
{
    // Look up the buffer from the sound name
    ALuint &bufid = BufferMap[name];
    // If the buffer doesn't exist, load the sound from disk
    if(bufid == 0)
        bufid = LoadSoundFromFile(name);

    ... get a source and play bufid ...
}

Of course, this only applies for non-streaming sounds, ones you would fully 
load before playing. You'll also want to periodically clear out BufferMap, so 
you don't waste memory by holding sounds that won't be played again.

Also note that you'll typically want to be able to set a sound's properties 
(position, volume, etc) /before/ it actually plays; so you'd either want to 
pass in initial values to PlaySound, or get a handle separately to set the 
properties before playing it.

> I look forward to getting some feedback on these designs.  Note, I am only
> talking about load and play sounds here.  I think I understand how to
> handle the streaming of an ogg file, by loading the compressed data into
> memory and then decompressing and streaming from the location in memory.

Typically as long as you're not on a CD drive or over a network, there's not 
much of a problem to stream it directly from disk. You don't need to load the 
file completely into memory even if it is compressed (the OS will typically do 
a good job of buffer the file into memory for you anyway).


More information about the Openal mailing list