Manage Audio with Audio Mixer in Unity
How did you manage the Audio in your game? Did you ever heard Audio Mixer in Unity? Did you manage the AudioSource one by one?
Well, ever heard about Audio Mixer in unity? What is it?
The Unity Audio Mixer allows you to mix various audio sources, apply effects to them, and perform mastering. — Unity manual
In this case, i would like to tell you how manage Background Music and SFX using Audio Mixer. First thing to do, prepare the asset, you can use from asset store. Then, open Audio Mixer window, click window -> Audio -> Audio Mixer
in Audio mixer window click plus button “+” to create Audio Mixer file, name it AudioMaster.
There is a Groups, click “+” to create new Audio Groups Under master. Create, BGM group and sfx group like this
If you want to know about Audio Group, you can read from the unity manual, here. Using Audio Group, we can group our audio by type that we want. Example, if you want minimize the volume of bgm, just use bgm audio group, if you want minimize sfx volume you can use sfx audio group, and more interesting, if you want to minimize the volume all of the audio, you can use master audio group, so you don’t have to minimize one by one the audio.
Check in your project window, it should like this.
Preparing scene
let’s prepare the scene. Add 3 audio source in hierarchy, the one is bgm and the other are sfx.
Click the bgm audio source, check the inspector, there is an Output value for audio mixer, drag and drop bgm audio group into output value in bgm audio source like this
setup sfx audio source like bgm audio source, drag and drop sfx audio group into output sfx audio source.
then add 3 slider ui in canvas for handling the volume.
Code
Create a script to handle the volume. I name it AudioManager. Before we start to code, let open the audio mixer window again. Click master audio group, then check inspector, right click in volume text, then choose expose volume to script. It means the audio group will be able to edit by script. Set the others too. 3 exposed parameter will be able into Exposed Parameter, and will be named into unity default parameter. It can be renamed by double click the parameter. In this case, i rename all of them.
Use AudioMixer Scripting Api.
Add the script into the scene
Assign set method from AudioManager into OnValueChanged event for each slider (sfx, bgm, master).
Play! When you play the scene, look closely audio mixer window, there is indicator showing the volume. Slide to left or right the slider, the indicator will be following the value.
You can manually setup the volume in each audio group. If the value to minimize or maximize to small, you can multiply with Time.deltatime or something float value in script.
Hope you enjoy it !! Cheers :)