summaryrefslogtreecommitdiff
path: root/Assets/Thirdparty/Tayx/Graphy - Ultimate Stats Monitor/Scripts/Audio/G_AudioMonitor.cs
blob: 74ce7579dcea4665215bedfe46c6e563a4f242d7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/* ---------------------------------------
 * Author:          Martin Pane (martintayx@gmail.com) (@tayx94)
 * Collaborators:   Lars Aalbertsen (@Rockylars)
 * Project:         Graphy - Ultimate Stats Monitor
 * Date:            15-Dec-17
 * Studio:          Tayx
 * 
 * This project is released under the MIT license.
 * Attribution is not required, but it is always welcomed!
 * -------------------------------------*/

using UnityEngine;
using UnityEngine.SceneManagement;

namespace Tayx.Graphy.Audio
{
    public class G_AudioMonitor : MonoBehaviour
    {
        /* ----- TODO: ----------------------------
         * Add summaries to the variables.
         * Add summaries to the functions.
         * Make the "FindAudioListener" not constantly use "Camera.main".
         * --------------------------------------*/

        #region Variables -> Private

        private const   float                               m_refValue                          = 1f;

        private         GraphyManager                       m_graphyManager                     = null;

        private         AudioListener                       m_audioListener                     = null;

        private         GraphyManager.LookForAudioListener  m_findAudioListenerInCameraIfNull   = GraphyManager.LookForAudioListener.ON_SCENE_LOAD;

        private         FFTWindow                           m_FFTWindow                         = FFTWindow.Blackman;

        private         int                                 m_spectrumSize                      = 512;

        private         float[]                             m_spectrum;
        private         float[]                             m_spectrumHighestValues;

        private         float                               m_maxDB;

        #endregion

        #region Properties -> Public

        /// <summary>
        /// Current audio spectrum from the specified AudioListener.
        /// </summary>
        public float[] Spectrum                 { get { return m_spectrum; } }

        /// <summary>
        /// Highest audio spectrum from the specified AudioListener in the last few seconds.
        /// </summary>
        public float[] SpectrumHighestValues    { get { return m_spectrumHighestValues; } }

        /// <summary>
        /// Maximum DB registered in the current spectrum.
        /// </summary>
        public float MaxDB                      { get { return m_maxDB; } }

        /// <summary>
        /// Returns true if there is a reference to the audio listener.
        /// </summary>
        public bool SpectrumDataAvailable       {  get { return m_audioListener != null;} }

        #endregion

        #region Methods -> Unity Callbacks

        private void Awake()
        {
            Init();
        }

        private void Update()
        {
            if (m_audioListener != null)
            {
                // Use this data to calculate the dB value

                AudioListener.GetOutputData(m_spectrum, 0);

                float sum = 0;

                for (int i = 0; i < m_spectrum.Length; i++)
                {
                    sum += m_spectrum[i] * m_spectrum[i]; // sum squared samples
                }

                float rmsValue = Mathf.Sqrt(sum / m_spectrum.Length); // rms = square root of average

                m_maxDB = 20 * Mathf.Log10(rmsValue / m_refValue); // calculate dB

                if (m_maxDB < -80) m_maxDB = -80; // clamp it to -80dB min

                // Use this data to draw the spectrum in the graphs

                AudioListener.GetSpectrumData(m_spectrum, 0, m_FFTWindow);

                for (int i = 0; i < m_spectrum.Length; i++)
                {
                    // Update the highest value if its lower than the current one
                    if (m_spectrum[i] > m_spectrumHighestValues[i])
                    {
                        m_spectrumHighestValues[i] = m_spectrum[i];
                    }

                    // Slowly lower the value 
                    else
                    {
                        m_spectrumHighestValues[i] = Mathf.Clamp
                        (
                            value: m_spectrumHighestValues[i] - m_spectrumHighestValues[i] * Time.deltaTime * 2,
                            min: 0,
                            max: 1
                        );
                    }
                }
            }
            else if(     m_audioListener == null 
                     &&  m_findAudioListenerInCameraIfNull == GraphyManager.LookForAudioListener.ALWAYS)
            {
                m_audioListener = FindAudioListener();
            }
        }

        private void OnDestroy()
        {
            UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded;
        }

        #endregion

        #region Methods -> Public

        public void UpdateParameters()
        {
            m_findAudioListenerInCameraIfNull   = m_graphyManager.FindAudioListenerInCameraIfNull;

            m_audioListener                     = m_graphyManager.AudioListener;
            m_FFTWindow                         = m_graphyManager.FftWindow;
            m_spectrumSize                      = m_graphyManager.SpectrumSize;

            if (m_audioListener == null
                    && m_findAudioListenerInCameraIfNull != GraphyManager.LookForAudioListener.NEVER)
            {
                m_audioListener = FindAudioListener();
            }

            m_spectrum              = new float[m_spectrumSize];
            m_spectrumHighestValues = new float[m_spectrumSize];
        }

        /// <summary>
        /// Converts spectrum values to decibels using logarithms.
        /// </summary>
        /// <param name="linear"></param>
        /// <returns></returns>
        public float lin2dB(float linear)
        {
            return Mathf.Clamp(Mathf.Log10(linear) * 20.0f, -160.0f, 0.0f);
        }

        /// <summary>
        /// Normalizes a value in decibels between 0-1.
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public float dBNormalized(float db)
        {
            return (db + 160f) / 160f;
        }

        #endregion

        #region Methods -> Private

        /// <summary>
        /// Tries to find an audio listener in the main camera.
        /// </summary>
        private AudioListener FindAudioListener()
        {
            Camera mainCamera = Camera.main;

            if (mainCamera != null)
            {
                return mainCamera.GetComponent<AudioListener>();
            }
            else
            {
                return null;
            }
        }

        private void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
        {
            if (m_findAudioListenerInCameraIfNull == GraphyManager.LookForAudioListener.ON_SCENE_LOAD)
            {
                m_audioListener = FindAudioListener();
            }
        }

        private void Init()
        {
            m_graphyManager = transform.root.GetComponentInChildren<GraphyManager>();
            
            UpdateParameters();

            UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
        }

        #endregion
    }
}