I’ve been working on a Sound/Music system that can be toggled off and on for some time now. It has taken an insane amount of work to get it working right without bugs (and it still has some bugs). But basically I have three components that go into this sound system.
This has probably been one of the most difficult things I’ve had to work on. I also had to make sure that the toggles state carries across each of my scenes. I’m currently using localStorage to achieve this.
- A playerData.js file which just contains an object that functions similar to a JSON file. I have two properties, soundOn and musicOn which you will see in a moment I use to determine the icon that displays and the current state of the sound/music.
- A Music.js (or Sound.js) class that does two things, first it allows me to pass in the sound file I want to use and second it contains two functions, one to playMusic and the other to stopMusic. I found it better to make some custom functions so that I can access them off of the object in the next class I am going to mention.
- A MusicToggle.js (or SoundToggle.js) class. This is the largest class in this system. It determines how the toggling works and how that impacts the sounds in the game. It’s a simple idea but took a lot of tweaking.
Here is the first conditional expanded.
The functioning product looks like this. I had to use custom functions to stop and play the sounds/music so that the music toggle didn’t affect the game sounds and the sound toggle didn’t affect the music.
Both are enabled:
Both are disabled
Sound is Disabled