From 02c991e5ea1ec93c8245157a3f174b547774a7e3 Mon Sep 17 00:00:00 2001 From: Star Rauchenberger Date: Sat, 13 Mar 2021 14:58:50 -0500 Subject: Sound volume is controllable from settings menu #7 --- src/menu_system.cpp | 7 +++++-- src/mixer.cpp | 12 +++++++++++- src/mixer.h | 5 +++++ 3 files changed, 21 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/menu_system.cpp b/src/menu_system.cpp index c099afe..a430009 100644 --- a/src/menu_system.cpp +++ b/src/menu_system.cpp @@ -65,8 +65,11 @@ void MenuSystem::openPauseMenu() { game_.getMixer().setMusicVolume(menuItem.value); }), MenuBuilder().Slider("Sound Volume: ") - .InitialValue(10) - .MaxValue(10), + .InitialValue(game_.getMixer().getSoundVolume()) + .MaxValue(10) + .SelectionChangedFunction([this] (MenuItem& menuItem) { + game_.getMixer().setSoundVolume(menuItem.value); + }), MenuBuilder().Command("Back") .ActivationFunction([this] (Game& game) { closePauseMenu(); diff --git a/src/mixer.cpp b/src/mixer.cpp index 74a870a..6071fca 100644 --- a/src/mixer.cpp +++ b/src/mixer.cpp @@ -4,9 +4,12 @@ void Mixer::playSound(std::string_view filename) { Mix_Chunk* chunk = getChunkByFilename(std::string(filename)); - if (Mix_PlayChannel(-1, chunk, 0) == -1) { + int ret = Mix_PlayChannel(-1, chunk, 0); + if (ret == -1) { throw mix_error(); } + + Mix_Volume(ret, soundVolume_); } int Mixer::loopSound(std::string_view filename) { @@ -17,6 +20,8 @@ int Mixer::loopSound(std::string_view filename) { throw mix_error(); } + Mix_Volume(ret, soundVolume_); + return ret; } @@ -32,6 +37,11 @@ void Mixer::unpauseSounds() { Mix_Resume(-1); } +void Mixer::setSoundVolume(int vol) { + soundVolume_ = MIX_MAX_VOLUME / 10.0 * vol; + Mix_Volume(-1, soundVolume_); +} + void Mixer::playMusic(std::string_view name, int ms) { Mix_Music* song = getMusicByName(name); int ret; diff --git a/src/mixer.h b/src/mixer.h index c2a0681..f9c958a 100644 --- a/src/mixer.h +++ b/src/mixer.h @@ -77,6 +77,10 @@ public: void unpauseSounds(); + int getSoundVolume() const { return std::round(static_cast(soundVolume_) / MIX_MAX_VOLUME * 10); } + + void setSoundVolume(int vol); + // name is the name of the file, not containing the extension // ms is the time in milliseconds to fade in void playMusic(std::string_view name, int ms = 0); @@ -113,6 +117,7 @@ private: std::string playingTrack_; int musicVolume_ = MIX_MAX_VOLUME; bool musicMuted_ = false; + int soundVolume_ = MIX_MAX_VOLUME; }; #endif /* end of include guard: MIXER_H_6DF82000 */ -- cgit 1.4.1