Sound system
Last, but definitely not least, the sound system deserves a brief overview. It probably would be a surprise to nobody at this point to learn that sounds are also reliant upon application states, which is why we're inheriting from StateDependent
again:
class SoundManager : public StateDependent{ public: SoundManager(AudioManager* l_audioMgr); ~SoundManager(); void ChangeState(const StateType& l_state); void RemoveState(const StateType& l_state); void Update(float l_dT); SoundID Play(const std::string& l_sound, const sf::Vector3f& l_position, bool l_loop = false, bool l_relative = false); bool Play(const SoundID& l_id); bool Stop(const SoundID& l_id); bool Pause(const SoundID& l_id); bool PlayMusic(const std::string& l_musicId, float l_volume = 100.f, bool l_loop = false); bool PlayMusic(const StateType& l_state); bool StopMusic(const StateType& l_state); bool PauseMusic(const StateType& l_state); bool SetPosition(const SoundID& l_id, const sf::Vector3f& l_pos); bool IsPlaying(const SoundID& l_id) const; SoundProps* GetSoundProperties(const std::string& l_soundName); static const int Max_Sounds = 150; static const int Sound_Cache = 75; private: ... AudioManager* m_audioManager; };
The AudioManager
class is responsible for managing auditory resources, in the same way textures and fonts are managed elsewhere. One of the bigger differences here is that we can actually play sounds in 3D space, hence the use of a sf::Vector3f
structure wherever a position needs to be represented. Sounds are also grouped by specific names, but there is a slight twist to this system. SFML can only handle about 255 different sounds playing all at once, which includes sf::Music
instances as well. It's because of this that we have to implement a recycling system that utilizes discarded instances of sounds, as well as a static limit of the maximum number of sounds allowed all at once.
Every different sound that is loaded and played has specific set up properties that can be tweaked. They are represented by this data structure:
struct SoundProps{ SoundProps(const std::string& l_name): m_audioName(l_name), m_volume(100), m_pitch(1.f), m_minDistance(10.f), m_attenuation(10.f){} std::string m_audioName; float m_volume; float m_pitch; float m_minDistance; float m_attenuation; };
audioName
is simply the identifier of the audio resource that is loaded in memory. The volume of a sound can obviously be tweaked, as well as its pitch. The last two properties are slightly more intricate. A sound at a point in space would begin to grow quieter and quieter, as we begin to move away from it. The minimum distance property describes the unit distance from the sound source, after which the sound begins to lose its volume. The rate at which this volume is lost after that point is reached is described by the attenuation factor.