diff --git a/src/game_launcher.cpp b/src/game_launcher.cpp index ee526bee2da..54ea90f1606 100644 --- a/src/game_launcher.cpp +++ b/src/game_launcher.cpp @@ -112,6 +112,7 @@ game_launcher::game_launcher(const commandline_options& cmdline_opts, const char main_event_context_(), hotkey_manager_(), music_thinker_(), + music_muter_(), test_scenario_("test"), screenshot_map_(), screenshot_filename_(), diff --git a/src/game_launcher.hpp b/src/game_launcher.hpp index 48baee3681d..ceb27aceb6b 100644 --- a/src/game_launcher.hpp +++ b/src/game_launcher.hpp @@ -114,6 +114,7 @@ private: const events::event_context main_event_context_; const hotkey::manager hotkey_manager_; sound::music_thinker music_thinker_; + sound::music_muter music_muter_; std::string test_scenario_; diff --git a/src/sound.cpp b/src/sound.cpp index c241c1149bd..f09b4356672 100644 --- a/src/sound.cpp +++ b/src/sound.cpp @@ -618,6 +618,30 @@ void music_thinker::process(events::pump_info &info) { } } +music_muter::music_muter() : + events::sdl_handler(false) +{ + join_global(); +} + +void music_muter::handle_window_event(const SDL_Event& event) +{ + if (preferences::music_on()) + { + if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) + { + Mix_ResumeMusic(); + } + else if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) + { + if (Mix_PlayingMusic()) + { + Mix_PauseMusic(); + } + } + } +} + void commit_music_changes() { played_before.clear(); diff --git a/src/sound.hpp b/src/sound.hpp index f3e63fc441d..e7de138f494 100644 --- a/src/sound.hpp +++ b/src/sound.hpp @@ -85,6 +85,14 @@ class music_thinker : public events::pump_monitor { void process(events::pump_info &info); }; +// A class to mute music when the game is in background +class music_muter : public events::sdl_handler { +public: + music_muter(); + void handle_event(const SDL_Event&) override {} + void handle_window_event(const SDL_Event& event) override; +}; + // Save music playlist for snapshot void write_music_play_list(config& snapshot);