globally available functions and resources

I'm planning to write something like a soundmanager for my games. There will only be one such a manager and everything that makes noise will use it.
What will be the better option

  • variables and functions in a namespace.

  • a class with only static members and functions

  • singleton class

What would you do, and why ?
Thnx for stopping by;-)


Variable and function in a namespace if you want to stick to C++ style,
Class and only static things if you wanna make it C style.

In ANY case, not a singleton one. Why ? Because it looks awful.

If I were doing it in C++ I would go with #1 as it's the case which will allow the best control over the api when mixed with other api's.


If there's one of those patterns that you've not practiced, it may be an opportunity to try. In this case, you can't shoot yourself in the foot : the sound system depends on a unique resource which is your PC's sound output, you are not likely to suddenly need multiple concurrent sound systems.

Otherwise, I would use whatever looks the most like the neighboring code.
For example if your code is mostly doing allegro5 calls like al_something(), I would prefer to have snd_something(), rather than Sound.Something()

Mark Oates

For a sound manager, I would probably go with an object, something like this:

1class Sound 2{ 3private: 4 class SoundRecord 5 { 6 public: 7 std::string identifier; 8 ALLEGRO_SAMPLE *sample; 9 // ... 10 }; 11 std::vector<SoundRecord *> samples; 12 13public: 14 // some methods like... 15 bool preload(std::string identifier, std::string filename); 16 void play(std::string identifier); 17 void start_stream(std::string identifier); 18 void fade_out(std::string identifier, float speed); 19 // ... 20};

Focus on the interface you want more than anything else. :)


It is gonna use allegro anyway..
but I need a nicer way of loading and playing sounds than the hard coded mess I have right now. I also need a way to play continues sound (loop) and stop the correct instance at the right moment. Right now I use a sample ID returned from al_play_sound and a bool that tells me if that instance is playing. But when you have a lot of looping sounds that must be stopped at the right moment.. it's not such a nice solution.

I also noticed you cannot compare sampleIDs ... ??


Last time I had such need, I linked it the opposite way : If an emitted sound could be cancelled / interrupted later ("Ka-me-ha-me... - Ouch!"), the emitter passed his own identifier.
It was a bit long ago, but I think I used the memory address of the calling class instance, stored as a void pointer. The code handling a game character would typically call play_sound("kamehama", this), or if the sound had to run to completion no matter what, it would be play_sound("boom", NULL)

Thread #616287. Printed from