Adding volume control with Audio Mixers

Sound volume adjustment can be a very important feature, especially if your game is a standalone. After all, it can be very frustrating to access the operational system volume control. In this recipe, we will use the new Audio Mixer feature to create independent volume controls for Music and Sound FX.

Getting ready

For this recipe, we have provided a Unity package named Volume.unitypackage, containing an initial scene featuring soundtrack music and sound effects. The file is available inside the 1362_09_05 folder.

How to do it...

To add volume control sliders to your scene, follow these steps:

  1. Import Volume.unitypackage into your project.
  2. Open the Volume scene (available in the Assets | Volume folder). Play the scene and walk towards the semitransparent green wall in the tunnel, using the W A S D keys (while pressing the Shift key to run). You will be able to listen to:
    • A looping soundtrack music
    • Bells ringing
    • A robotic speech whenever the character collides with the wall
  3. From the Project view, use the Create drop-down menu to add Audio Mixer to the project. Name it MainMixer. Double-click on it to open the Audio Mixer window.
  4. From the Groups view, highlight Master and click the + sign to add a child to the Master group. Name it Music. Then, highlight Master again and add a new child group named FX, as shown in the following screenshot:
    How to do it...
  5. From the Mixers view, highlight MainMixer and click the + sign to add a new Mixer to the project. Name it MusicMixer. Then, drag it into the MainMixer and select the Music group as its Output. Repeat the operation to add a mixer named FxMixer to the project by selecting the FX group as its output:
    How to do it...
  6. Now, select MusicMixer. Select its Master group and add a child named Soundtrack. Then, select FxMixer and add two children to its Master group: one named Speech, and another named Bells, as shown:
    How to do it...
  7. From the Hierarchy view, select the DialogueTrigger object. Then, in the Inspector view, change its Output track to FxMixer | Speech in the Audio Source component:
    How to do it...
  8. Now, select the Soundtrack GameObject. From the Inspector view, find the Audio Source component and change its Output track to MusicMixer | Soundtrack:
    How to do it...
  9. Finally, from the Assets folder in the Project view, select the Signal prefab . From the Inspector view, access its Audio Source component and change its Output to FxMixer | Bells:
    How to do it...
  10. From the Audio Mixer window, choose MainMixer and select its Master track. Then, from the Inspector view, right-click on Volume in the Attenuation component. From the context menu, select Expose 'Volume (of Master) to script as shown in the following screenshot. Repeat the operation for the Music and FX tracks:
    How to do it...
  11. From the top of the Audio Mixer with the MainMixer selected, access the Exposed Parameters drop-down menu. Then, right-click on MyExposedParam and rename it to OverallVolume. Then, rename MyExposedParam1 as MusicVolume and MyExposedParam2 as FxVolume.
  12. From the Project view, create a new C# Script and rename it to VolumeControl.
  13. Open the script in your editor and replace everything with the following code:
    using UnityEngine;
    
    using UnityEngine.Audio;
    using System.Collections;
    
    public class VolumeControl : MonoBehaviour{
      public AudioMixer myMixer;
      private GameObject panel;
      private bool isPaused = false;
    
      void Start(){
        panel = GameObject.Find("Panel");
        panel.SetActive(false);
      }
    
      void Update() {
        if (Input.GetKeyUp (KeyCode.Escape)) {
          panel.SetActive(!panel.activeInHierarchy);
    
          if(isPaused)
            Time.timeScale = 1.0f;
          else
            Time.timeScale = 0.0f;
    
          isPaused = !isPaused;
        }
      }
    
      public void ChangeMusicVol(float vol){
        myMixer.SetFloat ("MusicVolume", Mathf.Log10(vol) * 20f);
      }
    
      public void ChangeFxVol(float vol){
        myMixer.SetFloat ("FxVolume", Mathf.Log10(vol) * 20f);
      }
    
      public void ChangeOverallVol(float vol){
        myMixer.SetFloat ("OverallVolume", Mathf.Log10(vol) * 20f);
      }
    }
  14. From the Hierarchy view, use the Create dropdown menu to add a Panel to the scene (Create | UI | Panel). Note that it will automatically add a Canvas to the scene.
  15. From the Hierarchy view, use the Create dropdown menu to add a Slider to the scene (Create | UI | Slider). Make it a child of the Panel object.
  16. Rename the slider as OverallSlider. Duplicate it and rename the new copy to MusicSlider. Then, in the Inspector view, Rect Transform component, change its Pos Y parameter to -40.
  17. Duplicate MusicSlider and rename the new copy to FxSlider. Then, change its Pos Y parameter to -70:
    How to do it...
  18. Select the Canvas GameObject and add the VolumeControl script to it. Then, populate the MyMixer field of Volume Control with MainMixer:
    How to do it...
  19. Select the OverallSlider component. From the Inspector view at the Slider component, change Min Value to 0.000025 (or 2.5e-05). Then, below the On Value Changed list, click the + sign to add an action. From Hierarchy panel, drag Canvas into the Object slot and using the drop-down menu, choose VolumeControl | ChangeOverallVol option, as shown in the following screenshot, For testing purposes, change the appropriate selector from Runtime Only to Editor and Runtime.
    How to do it...
  20. Repeat the previous step with MusicSlider and FxSlider, but this time, choose ChangeMusicVol and ChangeFxVol options respectively from the drop-down menu.
  21. Play the scene. You will be able to access the sliders when pressing Escape on your keyboard and adjust volume settings from there.

How it works...

The new Audio Mixer feature works in a similar fashion to Digital Audio Workstations, such as Logic and Sonar. Through Audio Mixers, you can organize and manage audio elements by routing them into specific groups that can have individual audio tracks to be tweaked around, allowing for adjustments in volume level and sound effects.

By organizing and routing our audio clips into two groups (Music and FX), we established the MainMixer as a unified controller for volume. Then, we have used the Audio Mixer to expose the volume levels for each track of the MainMixer, making them accessible to our script.

Also, we have set up a basic GUI featuring three sliders that, when in use, will pass their float values (between 0.000025 and 1) as arguments to three specific functions in our script: ChangeMusicVol, ChangeFxVol, and ChangeOverallVol. These functions, on their turn, use the SetFloat command to effectively change the volume levels at runtime. However, before passing on the new volume levels, the script converts linear values (between 0.000025 and 1) to the decibel levels that are used by the Audio Mixer. This conversion is calculated through the log(x) * 20 mathematical function.

Note

For a full explanation on issues regarding the conversion of linear values to decibel levels and vice-versa, check out Aaron Brown's excellent article at http://www.playdotsound.com/portfolio-item/decibel-db-to-float-value-calculator-making-sense-of-linear-values-in-audio-tools/.

It's worth mentioning that the VolumeControl script also includes code to enable and disable the GUI and the EventSystem, depending upon if the player hits the Escape key to activate/deactivate the volume control sliders.

A very important note—do not change the volume of any MainMixer's tracks; leave them at 0 dB. The reason is that our VolumeControl script sets their maximum volume level. For general adjustments, use the secondary Mixers MusicMixer and FxMixer.

There's more...

Here is some extra information on Audio Mixers.

Playing with Audio Production

There are many creative uses for exposed parameters. We can, for instance, add effects such as Distortion, Flange, and Chorus to audio channels, allowing users to operate virtual sound tables/mixing boards.

See also

  • The Making a dynamic soundtrack with Snapshots recipe in this chapter
  • The Balancing the in-game audio with Ducking in this chapter
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.192.183