Search Unity

Audio Source and Audio Listener fixes

Discussion in 'Made With Unity' started by Jessy, Sep 12, 2008.

  1. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    I added a script to the wiki so that we all can have improved audio volume control in Unity. It's really simple; I just figured I would put it here because I think it would be useful to everybody who employs sound in their projects. Check out this thread for information on why this is useful.
     
  2. Dark3D

    Dark3D

    Joined:
    Aug 30, 2008
    Posts:
    53
    Thanks! Thats a great help! I was just working on a project that needed sound control too!

    Starr
     
  3. Morgan

    Morgan

    Joined:
    May 21, 2006
    Posts:
    1,223
    A great addition! Thanks.
     
  4. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
  5. Scrat

    Scrat

    Joined:
    Apr 20, 2008
    Posts:
    316
    I don't know if it's possible in Javascript but in C# there is what they call properties. It allows you to modify a variable and also do other stuffs at the same time.

    Here is your code:
    Code (csharp):
    1. var volume : float = 1;
    2.  
    3. // determines whether "RefreshVolume" will run in Update(),
    4. // or must be called manually
    5. var performanceMode = false;
    6.  
    7. private var loudnessExponent = Mathf.Log(Mathf.Sqrt(10), 2);
    8.  
    9. function RefreshVolume ()
    10.     {audioListener.volume = Mathf.Pow(volume, loudnessExponent);}
    11.  
    12. function Start ()
    13.     {RefreshVolume ();}
    14.  
    15. function Update ()
    16. {
    17. if (performanceMode == false)
    18.              RefreshVolume ();
    19. }
    Here is what he would become (untested)
    Code (csharp):
    1.  
    2. //C#
    3. private float m_iVolume = 1.0f;
    4. private float m_iLoudnessExponent = Mathf.Log(Mathf.Sqrt(10), 2);
    5. public float Volume
    6. {
    7.   get {return m_iVolume;}
    8.   set
    9.   {
    10.     m_iVolume = value;
    11.     RefreshVolume();
    12.   }
    13. }
    14.  
    15. void RefreshVolume()
    16. {
    17.   audioListener.volume = Mathf.Pow(m_iVolume, m_iLoudnessExponent);}
    18. }
    19.  
    20. void Start()
    21. {
    22.   Volume = 0.5f; // This way it updates the variable and calls RefreshVolume()
    23. }
    24.  
    Again this is untested but you should get the idea.
    I find properties super usefuls in C#...
     
  6. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
  7. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325