BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / AudioManager / Scripts / Audio / AudioManager.cs

AudioManager.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
AudioManager.cs 12.7 KiB Download Raw
1using UnityEngine;
2using UnityEngine.Audio;
3using System.Collections;
4using System.Collections.Generic;
5#if UNITY_EDITOR
6using UnityEditor;
7using System;
8using System.Reflection;
9#endif
10
11namespace OVR
12{
13
14public enum PreloadSounds {
15 Default, // default unity behavior
16 Preload, // audio clips are forced to preload
17 ManualPreload, // audio clips are forced to not preload, preloading must be done manually
18}
19
20public enum Fade
21{
22 In,
23 Out
24}
25
26[System.Serializable]
27public class SoundGroup {
28 public SoundGroup( string name ) {
29 this.name = name;
30 }
31 public SoundGroup() {
32 mixerGroup = null;
33 maxPlayingSounds = 0;
34 preloadAudio = PreloadSounds.Default;
35 volumeOverride = 1.0f;
36 }
37 public void IncrementPlayCount() {
38 playingSoundCount = Mathf.Clamp( ++playingSoundCount, 0, maxPlayingSounds );
39 }
40 public void DecrementPlayCount() {
41 playingSoundCount = Mathf.Clamp( --playingSoundCount, 0, maxPlayingSounds );
42 }
43 public bool CanPlaySound() {
44 return ( maxPlayingSounds == 0 ) || ( playingSoundCount < maxPlayingSounds );
45 }
46
47 public string name = string.Empty;
48 public SoundFX[] soundList = new SoundFX[0];
49 public AudioMixerGroup mixerGroup = null; // default = AudioManager.defaultMixerGroup
50 [Range(0,64)]
51 public int maxPlayingSounds = 0; // default = 0, unlimited
52 // TODO: this preload behavior is not yet implemented
53 public PreloadSounds preloadAudio = PreloadSounds.Default; // default = true, audio clip data will be preloaded
54 public float volumeOverride = 1.0f; // default = 1.0
55
56 [HideInInspector]
57 public int playingSoundCount = 0;
58}
59
60/*
61-----------------------
62
63 AudioManager
64
65-----------------------
66*/
67public partial class AudioManager : MonoBehaviour {
68
69 [Tooltip("Make the audio manager persistent across all scene loads")]
70 public bool makePersistent = true; // true = don't destroy on load
71 [Tooltip("Enable the OSP audio plugin features")]
72 public bool enableSpatializedAudio = true; // true = enable spatialized audio
73 [Tooltip("Always play spatialized sounds with no reflections (Default)")]
74 public bool enableSpatializedFastOverride = false; // true = disable spatialized reflections override
75 [Tooltip("The audio mixer asset used for snapshot blends, etc.")]
76 public AudioMixer audioMixer = null;
77 [Tooltip( "The audio mixer group used for the pooled emitters" )]
78 public AudioMixerGroup defaultMixerGroup = null;
79 [Tooltip( "The audio mixer group used for the reserved pool emitter" )]
80 public AudioMixerGroup reservedMixerGroup = null;
81 [Tooltip( "The audio mixer group used for voice chat" )]
82 public AudioMixerGroup voiceChatMixerGroup = null;
83 [Tooltip("Log all PlaySound calls to the Unity console")]
84 public bool verboseLogging = false; // true = log all PlaySounds
85 [Tooltip("Maximum sound emitters")]
86 public int maxSoundEmitters = 32; // total number of sound emitters created
87 [Tooltip("Default volume for all sounds modulated by individual sound FX volumes")]
88 public float volumeSoundFX = 1.0f; // user pref: volume of all sound FX
89 [Tooltip("Sound FX fade time")]
90 public float soundFxFadeSecs = 1.0f; // sound FX fade time
91
92 public float audioMinFallOffDistance = 1.0f; // minimum falloff distance
93 public float audioMaxFallOffDistance = 25.0f; // maximum falloff distance
94
95 public SoundGroup[] soundGroupings = new SoundGroup[0];
96
97 private Dictionary<string,SoundFX> soundFXCache = null;
98
99 static private AudioManager theAudioManager = null;
100 static private FastList<string> names = new FastList<string>();
101 static private string[] defaultSound = new string[1] { "Default Sound" };
102 static private SoundFX nullSound = new SoundFX();
103 static private bool hideWarnings = false;
104 static public bool enableSpatialization { get { return ( theAudioManager !=null ) ? theAudioManager.enableSpatializedAudio : false; } }
105
106 static public AudioManager Instance { get { return theAudioManager; } }
107 static public float NearFallOff { get { return theAudioManager.audioMinFallOffDistance; } }
108 static public float FarFallOff { get { return theAudioManager.audioMaxFallOffDistance; } }
109 static public AudioMixerGroup EmitterGroup { get { return theAudioManager.defaultMixerGroup; } }
110 static public AudioMixerGroup ReservedGroup { get { return theAudioManager.reservedMixerGroup; } }
111 static public AudioMixerGroup VoipGroup { get { return theAudioManager.voiceChatMixerGroup; } }
112
113 /*
114 -----------------------
115 Awake()
116 -----------------------
117 */
118 void Awake() {
119 Init();
120 }
121
122 /*
123 -----------------------
124 OnDestroy()
125 -----------------------
126 */
127 void OnDestroy() {
128 // we only want the initialized audio manager instance cleaning up the sound emitters
129 if ( theAudioManager == this ) {
130 if ( soundEmitterParent != null ) {
131 Destroy( soundEmitterParent );
132 }
133 }
134 ///TODO - if you change scenes you'll want to call OnPreSceneLoad to detach the sound emitters
135 ///from anything they might be parented to or they will get destroyed with that object
136 ///there should only be one instance of the AudioManager across the life of the game/app
137 ///GameManager.OnPreSceneLoad -= OnPreSceneLoad;
138 }
139
140 /*
141 -----------------------
142 Init()
143 -----------------------
144 */
145 void Init() {
146 if ( theAudioManager != null ) {
147 if ( Application.isPlaying && ( theAudioManager != this ) ) {
148 enabled = false;
149 }
150 return;
151 }
152 theAudioManager = this;
153
154 ///TODO - if you change scenes you'll want to call OnPreSceneLoad to detach the sound emitters
155 ///from anything they might be parented to or they will get destroyed with that object
156 ///there should only be one instance of the AudioManager across the life of the game/app
157 ///GameManager.OnPreSceneLoad += OnPreSceneLoad;
158
159 // make sure the first one is a null sound
160 nullSound.name = "Default Sound";
161
162 // build the sound FX cache
163 RebuildSoundFXCache();
164
165 // create the sound emitters
166 if ( Application.isPlaying ) {
167 InitializeSoundSystem();
168 if ( makePersistent && ( transform.parent == null ) ) {
169 // don't destroy the audio manager on scene loads
170 DontDestroyOnLoad( gameObject );
171 }
172 }
173
174#if UNITY_EDITOR
175 Debug.Log( "[AudioManager] Initialized..." );
176#endif
177 }
178
179 /*
180 -----------------------
181 Update()
182 -----------------------
183 */
184 void Update() {
185 // update the free and playing lists
186 UpdateFreeEmitters();
187 }
188
189 /*
190 -----------------------
191 RebuildSoundFXCache()
192 -----------------------
193 */
194 void RebuildSoundFXCache() {
195 // build the SoundFX dictionary for quick name lookups
196 int count = 0;
197 for ( int group = 0; group < soundGroupings.Length; group++ ) {
198 count += soundGroupings[group].soundList.Length;
199 }
200 soundFXCache = new Dictionary<string,SoundFX>( count + 1 );
201 // add the null sound
202 soundFXCache.Add( nullSound.name, nullSound );
203 // add the rest
204 for ( int group = 0; group < soundGroupings.Length; group++ ) {
205 for ( int i = 0; i < soundGroupings[group].soundList.Length; i++ ) {
206 if ( soundFXCache.ContainsKey( soundGroupings[group].soundList[i].name ) ) {
207 Debug.LogError( "ERROR: Duplicate Sound FX name in the audio manager: '" + soundGroupings[group].name + "' > '" + soundGroupings[group].soundList[i].name + "'" );
208 } else {
209 soundGroupings[group].soundList[i].Group = soundGroupings[group];
210 soundFXCache.Add( soundGroupings[group].soundList[i].name, soundGroupings[group].soundList[i] );
211 }
212 }
213 soundGroupings[group].playingSoundCount = 0;
214 }
215 }
216
217 /*
218 -----------------------
219 FindSoundFX()
220 -----------------------
221 */
222 static public SoundFX FindSoundFX( string name, bool rebuildCache = false ) {
223#if UNITY_EDITOR
224 if ( theAudioManager == null ) {
225 Debug.LogError( "ERROR: audio manager not yet initialized or created!" + " Time: " + Time.time );
226 return null;
227 }
228#endif
229 if ( string.IsNullOrEmpty( name ) ) {
230 return nullSound;
231 }
232 if ( rebuildCache ) {
233 theAudioManager.RebuildSoundFXCache();
234 }
235 if ( !theAudioManager.soundFXCache.ContainsKey( name ) ) {
236#if DEBUG_BUILD || UNITY_EDITOR
237 Debug.LogError( "WARNING: Missing Sound FX in cache: " + name );
238#endif
239 return nullSound;
240 }
241 return theAudioManager.soundFXCache[name];
242 }
243
244 /*
245 -----------------------
246 FindAudioManager()
247 -----------------------
248 */
249 static private bool FindAudioManager() {
250 GameObject audioManagerObject = GameObject.Find( "AudioManager" );
251 if ( ( audioManagerObject == null ) || ( audioManagerObject.GetComponent<AudioManager>() == null ) ) {
252 if ( !hideWarnings ) {
253 Debug.LogError( "[ERROR] AudioManager object missing from hierarchy!" );
254 hideWarnings = true;
255 }
256 return false;
257 } else {
258 audioManagerObject.GetComponent<AudioManager>().Init();
259 }
260 return true;
261 }
262
263 /*
264 -----------------------
265 GetGameObject()
266 -----------------------
267 */
268 static public GameObject GetGameObject() {
269 if ( theAudioManager == null ) {
270 if ( !FindAudioManager() ) {
271 return null;
272 }
273 }
274 return theAudioManager.gameObject;
275 }
276
277 /*
278 -----------------------
279 NameMinusGroup()
280 strip off the sound group from the inspector dropdown
281 -----------------------
282 */
283 static public string NameMinusGroup( string name ) {
284 if ( name.IndexOf( "/" ) > -1 ) {
285 return name.Substring( name.IndexOf( "/" ) + 1 );
286 }
287 return name;
288 }
289
290 /*
291 -----------------------
292 GetSoundFXNames()
293 used by the inspector
294 -----------------------
295 */
296 static public string[] GetSoundFXNames( string currentValue, out int currentIdx ) {
297 currentIdx = 0;
298 names.Clear();
299 if ( theAudioManager == null ) {
300 if ( !FindAudioManager() ) {
301 return defaultSound;
302 }
303 }
304 names.Add( nullSound.name );
305 for ( int group = 0; group < theAudioManager.soundGroupings.Length; group++ ) {
306 for ( int i = 0; i < theAudioManager.soundGroupings[group].soundList.Length; i++ ) {
307 if ( string.Compare( currentValue, theAudioManager.soundGroupings[group].soundList[i].name, true ) == 0 ) {
308 currentIdx = names.Count;
309 }
310 names.Add( theAudioManager.soundGroupings[group].name + "/" + theAudioManager.soundGroupings[group].soundList[i].name );
311 }
312 }
313 //names.Sort( delegate( string s1, string s2 ) { return s1.CompareTo( s2 ); } );
314 return names.ToArray();
315
316 }
317#if UNITY_EDITOR
318 /*
319 -----------------------
320 OnPrefabReimported()
321 -----------------------
322 */
323 static public void OnPrefabReimported() {
324 if ( theAudioManager != null ) {
325 Debug.Log( "[AudioManager] Reimporting the sound FX cache." );
326 theAudioManager.RebuildSoundFXCache();
327 }
328 }
329
330 /*
331 -----------------------
332 PlaySound()
333 used in the editor
334 -----------------------
335 */
336 static public void PlaySound( string soundFxName ) {
337 if ( theAudioManager == null ) {
338 if ( !FindAudioManager() ) {
339 return;
340 }
341 }
342 SoundFX soundFX = FindSoundFX( soundFxName, true );
343 if ( soundFX == null ) {
344 return;
345 }
346 AudioClip clip = soundFX.GetClip();
347 if ( clip != null ) {
348 Assembly unityEditorAssembly = typeof(AudioImporter).Assembly;
349 Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
350 MethodInfo method = audioUtilClass.GetMethod(
351 "PlayClip",
352 BindingFlags.Static | BindingFlags.Public,
353 null,
354 new System.Type[] { typeof(AudioClip) },
355 null );
356 method.Invoke( null, new object[] { clip } );
357 }
358 }
359
360 /*
361 -----------------------
362 IsSoundPlaying()
363 used in the editor
364 -----------------------
365 */
366 static public bool IsSoundPlaying( string soundFxName ) {
367 if ( theAudioManager == null ) {
368 if ( !FindAudioManager() ) {
369 return false;
370 }
371 }
372 SoundFX soundFX = FindSoundFX( soundFxName, true );
373 if ( soundFX == null ) {
374 return false;
375 }
376 AudioClip clip = soundFX.GetClip();
377 if ( clip != null ) {
378 Assembly unityEditorAssembly = typeof(AudioImporter).Assembly;
379 Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
380 MethodInfo method = audioUtilClass.GetMethod(
381 "IsClipPlaying",
382 BindingFlags.Static | BindingFlags.Public,
383 null,
384 new System.Type[] { typeof(AudioClip) },
385 null );
386 return Convert.ToBoolean( method.Invoke( null, new object[] { clip } ) );
387 }
388
389 return false;
390 }
391
392 /*
393 -----------------------
394 StopSound()
395 used in the editor
396 -----------------------
397 */
398 static public void StopSound(string soundFxName)
399 {
400 if (theAudioManager == null)
401 {
402 if (!FindAudioManager())
403 {
404 return;
405 }
406 }
407 SoundFX soundFX = FindSoundFX(soundFxName, true);
408 if (soundFX == null)
409 {
410 return;
411 }
412 AudioClip clip = soundFX.GetClip();
413 if (clip != null)
414 {
415 Assembly unityEditorAssembly = typeof(AudioImporter).Assembly;
416 Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
417 MethodInfo method = audioUtilClass.GetMethod(
418 "StopClip",
419 BindingFlags.Static | BindingFlags.Public,
420 null,
421 new System.Type[] { typeof(AudioClip) },
422 null);
423 method.Invoke(null, new object[] { clip });
424 }
425 }
426#endif
427}
428
429} // namespace OVR