BlueGit

blue-star ggj-2020

Files

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

AudioManager_Sound.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
AudioManager_Sound.cs 24.7 KiB Download Raw
1using UnityEngine;
2using UnityEngine.Audio;
3
4namespace OVR
5{
6
7//-------------------------------------------------------------------------
8// Types
9//-------------------------------------------------------------------------
10
11public enum EmitterChannel {
12 None = -1,
13 Reserved = 0, // plays on the single reserved emitter
14 Any // queues to the next available emitter
15}
16
17[System.Serializable]
18public class MixerSnapshot {
19 public AudioMixerSnapshot snapshot = null;
20 public float transitionTime = 0.25f;
21}
22
23/*
24-----------------------
25
26 GameManager Sound Routines
27
28-----------------------
29*/
30public partial class AudioManager : MonoBehaviour {
31
32 public enum Fade {
33 In,
34 Out
35 }
36
37 private float audioMaxFallOffDistanceSqr = 25.0f * 25.0f; // past this distance, sounds are ignored for the local player
38
39 private SoundEmitter[] soundEmitters = null; // pool of sound emitters to play sounds through
40
41 private FastList<SoundEmitter> playingEmitters = new FastList<SoundEmitter>();
42 private FastList<SoundEmitter> nextFreeEmitters = new FastList<SoundEmitter>();
43
44 private MixerSnapshot currentSnapshot = null;
45
46 static private GameObject soundEmitterParent = null; // parent object for the sound emitters
47 static private Transform staticListenerPosition = null; // play position for regular 2D sounds
48
49 static private bool showPlayingEmitterCount = false;
50 static private bool forceShowEmitterCount = false;
51
52 static private bool soundEnabled = true;
53 static public bool SoundEnabled { get { return soundEnabled; } }
54
55 static readonly AnimationCurve defaultReverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
56
57 /*
58 -----------------------
59 InitializeSoundSystem()
60 initialize persistent sound emitter objects that live across scene loads
61 -----------------------
62 */
63 void InitializeSoundSystem() {
64
65 int bufferLength = 960;
66 int numBuffers = 4;
67 AudioSettings.GetDSPBufferSize( out bufferLength, out numBuffers );
68 if ( Application.isPlaying ) {
69 Debug.Log( "[AudioManager] Audio Sample Rate: " + AudioSettings.outputSampleRate );
70 Debug.Log( "[AudioManager] Audio Buffer Length: " + bufferLength + " Size: " + numBuffers );
71 }
72
73 // find the audio listener for playing regular 2D sounds
74 AudioListener audioListenerObject = GameObject.FindObjectOfType<AudioListener>() as AudioListener;
75 if ( audioListenerObject == null ) {
76 Debug.LogError( "[AudioManager] Missing AudioListener object! Add one to the scene." );
77 } else {
78 staticListenerPosition = audioListenerObject.transform;
79 }
80
81 // we allocate maxSoundEmitters + reserved channels
82 soundEmitters = new SoundEmitter[maxSoundEmitters+(int)EmitterChannel.Any];
83
84 // see if the sound emitters have already been created, if so, nuke it, it shouldn't exist in the scene upon load
85 soundEmitterParent = GameObject.Find( "__SoundEmitters__" );
86 if ( soundEmitterParent != null ) {
87 // delete any sound emitters hanging around
88 Destroy( soundEmitterParent );
89 }
90
91 // create them all
92 soundEmitterParent = new GameObject( "__SoundEmitters__" );
93 for ( int i = 0; i < maxSoundEmitters + (int)EmitterChannel.Any; i++ ) {
94 GameObject emitterObject = new GameObject( "SoundEmitter_" + i );
95 emitterObject.transform.parent = soundEmitterParent.transform;
96 emitterObject.transform.position = Vector3.zero;
97 // don't ever save this to the scene
98 emitterObject.hideFlags = HideFlags.DontSaveInEditor;
99 // add the sound emitter components
100 soundEmitters[i] = emitterObject.AddComponent<SoundEmitter>();
101 soundEmitters[i].SetDefaultParent( soundEmitterParent.transform );
102 soundEmitters[i].SetChannel( i );
103 soundEmitters[i].Stop();
104 // save off the original index
105 soundEmitters[i].originalIdx = i;
106 }
107 // reset the free emitter lists
108 ResetFreeEmitters();
109 soundEmitterParent.hideFlags = HideFlags.DontSaveInEditor;
110
111 audioMaxFallOffDistanceSqr = audioMaxFallOffDistance * audioMaxFallOffDistance;
112 }
113
114 /*
115 -----------------------
116 UpdateFreeEmitters()
117 -----------------------
118 */
119 void UpdateFreeEmitters() {
120 if ( verboseLogging ) {
121 if ( Input.GetKeyDown( KeyCode.A ) ) {
122 forceShowEmitterCount = !forceShowEmitterCount;
123 }
124 if ( forceShowEmitterCount ) {
125 showPlayingEmitterCount = true;
126 }
127 }
128 // display playing emitter count when the sound system is overwhelmed
129 int total = 0, veryLow = 0, low = 0, def = 0, high = 0, veryHigh = 0;
130
131 // find emitters that are done playing and add them to the nextFreeEmitters list
132 for ( int i = 0; i < playingEmitters.size; ) {
133 if ( playingEmitters[i] == null ) {
134 Debug.LogError( "[AudioManager] ERROR: playingEmitters list had a null emitter! Something nuked a sound emitter!!!" );
135 playingEmitters.RemoveAtFast( i );
136 return;
137 }
138 if ( !playingEmitters[i].IsPlaying() ) {
139 // add to the free list and remove from the playing list
140 if ( verboseLogging ) {
141 if ( nextFreeEmitters.Contains( playingEmitters[i] ) ) {
142 Debug.LogError( "[AudioManager] ERROR: playing sound emitter already in the free emitters list!" );
143 }
144 }
145 playingEmitters[i].Stop();
146 nextFreeEmitters.Add( playingEmitters[i] );
147 playingEmitters.RemoveAtFast( i );
148 continue;
149 }
150 // debugging/profiling
151 if ( verboseLogging && showPlayingEmitterCount ) {
152 total++;
153 switch ( playingEmitters[i].priority ) {
154 case SoundPriority.VeryLow: veryLow++; break;
155 case SoundPriority.Low: low++; break;
156 case SoundPriority.Default: def++; break;
157 case SoundPriority.High: high++; break;
158 case SoundPriority.VeryHigh: veryHigh++; break;
159 }
160 }
161 i++;
162 }
163 if ( verboseLogging && showPlayingEmitterCount ) {
164 Debug.LogWarning( string.Format( "[AudioManager] Playing sounds: Total {0} | VeryLow {1} | Low {2} | Default {3} | High {4} | VeryHigh {5} | Free {6}", Fmt( total ), Fmt( veryLow ), Fmt( low ), Fmt( def ), Fmt( high ), Fmt( veryHigh ), FmtFree( nextFreeEmitters.Count ) ) );
165 showPlayingEmitterCount = false;
166 }
167 }
168
169 /*
170 -----------------------
171 Fmt()
172 -----------------------
173 */
174 string Fmt( int count ) {
175 float t = count / (float)theAudioManager.maxSoundEmitters;
176 if ( t < 0.5f ) {
177 return "<color=green>" + count.ToString() + "</color>";
178 } else if ( t < 0.7 ) {
179 return "<color=yellow>" + count.ToString() + "</color>";
180 } else {
181 return "<color=red>" + count.ToString() + "</color>";
182 }
183 }
184
185 /*
186 -----------------------
187 FmtFree()
188 -----------------------
189 */
190 string FmtFree( int count ) {
191 float t = count / (float)theAudioManager.maxSoundEmitters;
192 if ( t < 0.2f ) {
193 return "<color=red>" + count.ToString() + "</color>";
194 } else if ( t < 0.3 ) {
195 return "<color=yellow>" + count.ToString() + "</color>";
196 } else {
197 return "<color=green>" + count.ToString() + "</color>";
198 }
199 }
200
201 /*
202 -----------------------
203 OnPreSceneLoad()
204 -----------------------
205 */
206 void OnPreSceneLoad() {
207 // move any attached sounds back to the sound emitters parent before changing levels so they don't get destroyed
208 Debug.Log( "[AudioManager] OnPreSceneLoad cleanup" );
209 for ( int i = 0; i < soundEmitters.Length; i++ ) {
210 soundEmitters[i].Stop();
211 soundEmitters[i].ResetParent( soundEmitterParent.transform );
212 }
213 // reset our emitter lists
214 ResetFreeEmitters();
215 }
216
217 /*
218 -----------------------
219 ResetFreeEmitters()
220 -----------------------
221 */
222 void ResetFreeEmitters() {
223 nextFreeEmitters.Clear();
224 playingEmitters.Clear();
225 for ( int i = (int)EmitterChannel.Any; i < soundEmitters.Length; i++ ) {
226 nextFreeEmitters.Add( soundEmitters[i] );
227 }
228 }
229
230 /*
231 -----------------------
232 FadeOutSoundChannel()
233 utility function to fade out a playing sound channel
234 -----------------------
235 */
236 static public void FadeOutSoundChannel( int channel, float delaySecs, float fadeTime ) {
237 theAudioManager.soundEmitters[channel].FadeOutDelayed( delaySecs, fadeTime );
238 }
239
240 /*
241 -----------------------
242 StopSound()
243 -----------------------
244 */
245 static public bool StopSound( int idx, bool fadeOut = true, bool stopReserved = false ) {
246 if ( !stopReserved && ( idx == (int)EmitterChannel.Reserved ) ) {
247 return false;
248 }
249 if ( !fadeOut ) {
250 theAudioManager.soundEmitters[idx].Stop();
251 }
252 else {
253 theAudioManager.soundEmitters[idx].FadeOut( theAudioManager.soundFxFadeSecs );
254 }
255
256 return true;
257 }
258
259 /*
260 -----------------------
261 FadeInSound()
262 -----------------------
263 */
264 public static void FadeInSound( int idx, float fadeTime, float volume ) {
265 theAudioManager.soundEmitters[idx].FadeIn( fadeTime, volume );
266 }
267
268 /*
269 -----------------------
270 FadeInSound()
271 -----------------------
272 */
273 public static void FadeInSound( int idx, float fadeTime ) {
274 theAudioManager.soundEmitters[idx].FadeIn( fadeTime );
275 }
276
277 /*
278 -----------------------
279 FadeOutSound()
280 -----------------------
281 */
282 public static void FadeOutSound( int idx, float fadeTime ) {
283 theAudioManager.soundEmitters[idx].FadeOut( fadeTime );
284 }
285
286 /*
287 -----------------------
288 StopAllSounds()
289 -----------------------
290 */
291 public static void StopAllSounds( bool fadeOut, bool stopReserved = false ) {
292 for ( int i = 0; i < theAudioManager.soundEmitters.Length; i++ ) {
293 StopSound( i, fadeOut, stopReserved );
294 }
295 }
296
297 /*
298 -----------------------
299 MuteAllSounds()
300 -----------------------
301 */
302 public void MuteAllSounds( bool mute, bool muteReserved = false ) {
303 for ( int i = 0; i < soundEmitters.Length; i++ ) {
304 if ( !muteReserved && ( i == (int)EmitterChannel.Reserved ) ) {
305 continue;
306 }
307 soundEmitters[i].audioSource.mute = true;
308 }
309 }
310
311 /*
312 -----------------------
313 UnMuteAllSounds()
314 -----------------------
315 */
316 public void UnMuteAllSounds( bool unmute, bool unmuteReserved = false ) {
317 for ( int i = 0; i < soundEmitters.Length; i++ ) {
318 if ( !unmuteReserved && ( i == (int)EmitterChannel.Reserved ) ) {
319 continue;
320 }
321 if ( soundEmitters[i].audioSource.isPlaying ) {
322 soundEmitters[i].audioSource.mute = false;
323 }
324 }
325 }
326
327 /*
328 -----------------------
329 GetEmitterEndTime()
330 -----------------------
331 */
332 static public float GetEmitterEndTime( int idx ) {
333 return theAudioManager.soundEmitters[idx].endPlayTime;
334 }
335
336 /*
337 -----------------------
338 SetEmitterTime()
339 -----------------------
340 */
341 static public float SetEmitterTime( int idx, float time ) {
342 return theAudioManager.soundEmitters[idx].time = time;
343 }
344
345 /*
346 -----------------------
347 PlaySound()
348 -----------------------
349 */
350 static public int PlaySound( AudioClip clip, float volume, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float pitchVariance = 1.0f, bool loop = false ) {
351 if ( !SoundEnabled ) {
352 return -1;
353 }
354 return PlaySoundAt( ( staticListenerPosition != null ) ? staticListenerPosition.position : Vector3.zero, clip, volume, src, delay, pitchVariance, loop );
355 }
356
357 /*
358 -----------------------
359 FindFreeEmitter()
360 -----------------------
361 */
362 static private int FindFreeEmitter( EmitterChannel src, SoundPriority priority ) {
363 // default to the reserved emitter
364 SoundEmitter next = theAudioManager.soundEmitters[0];
365 if ( src == EmitterChannel.Any ) {
366 // pull from the free emitter list if possible
367 if ( theAudioManager.nextFreeEmitters.size > 0 ) {
368 // return the first in the list
369 next = theAudioManager.nextFreeEmitters[0];
370 // remove it from the free list
371 theAudioManager.nextFreeEmitters.RemoveAtFast( 0 );
372 } else {
373 // no free emitters available so pull from the lowest priority sound
374 if ( priority == SoundPriority.VeryLow ) {
375 // skip low priority sounds
376 return -1;
377 } else {
378 // find a playing emitter that has a lower priority than what we're requesting
379 // TODO - we could first search for Very Low, then Low, etc ... TBD if it's worth the effort
380 next = theAudioManager.playingEmitters.Find( item => item != null && item.priority < priority );
381 if ( next == null ) {
382 // last chance to find a free emitter
383 if ( priority < SoundPriority.Default ) {
384 // skip sounds less than the default priority
385 if ( theAudioManager.verboseLogging ) {
386 Debug.LogWarning( "[AudioManager] skipping sound " + priority );
387 }
388 return -1;
389 } else {
390 // grab a default priority emitter so that we don't cannabalize a high priority sound
391 next = theAudioManager.playingEmitters.Find( item => item != null && item.priority <= SoundPriority.Default ); ;
392 }
393 }
394 if ( next != null ) {
395 if ( theAudioManager.verboseLogging ) {
396 Debug.LogWarning( "[AudioManager] cannabalizing " + next.originalIdx + " Time: " + Time.time );
397 }
398 // remove it from the playing list
399 next.Stop();
400 theAudioManager.playingEmitters.RemoveFast( next );
401 }
402 }
403 }
404 }
405 if ( next == null ) {
406 Debug.LogError( "[AudioManager] ERROR - absolutely couldn't find a free emitter! Priority = " + priority + " TOO MANY PlaySound* calls!" );
407 showPlayingEmitterCount = true;
408 return -1;
409 }
410 return next.originalIdx;
411 }
412
413 /*
414 -----------------------
415 PlaySound()
416 -----------------------
417 */
418 static public int PlaySound( SoundFX soundFX, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f ) {
419 if ( !SoundEnabled ) {
420 return -1;
421 }
422 return PlaySoundAt( ( staticListenerPosition != null ) ? staticListenerPosition.position : Vector3.zero, soundFX, src, delay );
423 }
424
425 /*
426 -----------------------
427 PlaySoundAt()
428 -----------------------
429 */
430 static public int PlaySoundAt( Vector3 position, SoundFX soundFX, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float volumeOverride = 1.0f, float pitchMultiplier = 1.0f ) {
431 if ( !SoundEnabled ) {
432 return -1;
433 }
434
435 AudioClip clip = soundFX.GetClip();
436 if ( clip == null ) {
437 return -1;
438 }
439
440 // check the distance from the local player and ignore sounds out of range
441 if ( staticListenerPosition != null ) {
442 float distFromListener = ( staticListenerPosition.position - position ).sqrMagnitude;
443 if ( distFromListener > theAudioManager.audioMaxFallOffDistanceSqr ) {
444 return -1;
445 }
446 if ( distFromListener > soundFX.MaxFalloffDistSquared ) {
447 return -1;
448 }
449 }
450
451 // check max playing sounds
452 if ( soundFX.ReachedGroupPlayLimit() ) {
453 if ( theAudioManager.verboseLogging ) {
454 Debug.Log( "[AudioManager] PlaySoundAt() with " + soundFX.name + " skipped due to group play limit" );
455 }
456 return -1;
457 }
458
459 int idx = FindFreeEmitter( src, soundFX.priority );
460 if ( idx == -1 ) {
461 // no free emitters - should only happen on very low priority sounds
462 return -1;
463 }
464 SoundEmitter emitter = theAudioManager.soundEmitters[idx];
465
466 // make sure to detach the emitter from a previous parent
467 emitter.ResetParent( soundEmitterParent.transform );
468 emitter.gameObject.SetActive( true );
469
470 // set up the sound emitter
471 AudioSource audioSource = emitter.audioSource;
472 ONSPAudioSource osp = emitter.osp;
473
474 audioSource.enabled = true;
475 audioSource.volume = Mathf.Clamp01( Mathf.Clamp01( theAudioManager.volumeSoundFX * soundFX.volume ) * volumeOverride * soundFX.GroupVolumeOverride );
476 audioSource.pitch = soundFX.GetPitch() * pitchMultiplier;
477 audioSource.time = 0.0f;
478 audioSource.spatialBlend = 1.0f;
479 audioSource.rolloffMode = soundFX.falloffCurve;
480 if ( soundFX.falloffCurve == AudioRolloffMode.Custom ) {
481 audioSource.SetCustomCurve( AudioSourceCurveType.CustomRolloff, soundFX.volumeFalloffCurve );
482 }
483 audioSource.SetCustomCurve( AudioSourceCurveType.ReverbZoneMix, soundFX.reverbZoneMix );
484 audioSource.dopplerLevel = 0;
485 audioSource.clip = clip;
486 audioSource.spread = soundFX.spread;
487 audioSource.loop = soundFX.looping;
488 audioSource.mute = false;
489 audioSource.minDistance = soundFX.falloffDistance.x;
490 audioSource.maxDistance = soundFX.falloffDistance.y;
491 audioSource.outputAudioMixerGroup = soundFX.GetMixerGroup( AudioManager.EmitterGroup );
492 // set the play time so we can check when sounds are done
493 emitter.endPlayTime = Time.time + clip.length + delay;
494 // cache the default volume for fading
495 emitter.defaultVolume = audioSource.volume;
496 // sound priority
497 emitter.priority = soundFX.priority;
498 // reset this
499 emitter.onFinished = null;
500 // update the sound group limits
501 emitter.SetPlayingSoundGroup( soundFX.Group );
502 // add to the playing list
503 if ( src == EmitterChannel.Any ) {
504 theAudioManager.playingEmitters.AddUnique( emitter );
505 }
506
507 // OSP properties
508 if ( osp != null ) {
509 osp.EnableSpatialization = soundFX.ospProps.enableSpatialization;
510 osp.EnableRfl = theAudioManager.enableSpatializedFastOverride || soundFX.ospProps.useFastOverride ? true : false;
511 osp.Gain = soundFX.ospProps.gain;
512 osp.UseInvSqr = soundFX.ospProps.enableInvSquare;
513 osp.Near = soundFX.ospProps.invSquareFalloff.x;
514 osp.Far = soundFX.ospProps.invSquareFalloff.y;
515 audioSource.spatialBlend = (soundFX.ospProps.enableSpatialization) ? 1.0f : 0.8f;
516
517 // make sure to set the properties in the audio source before playing
518 osp.SetParameters(ref audioSource);
519 }
520
521 audioSource.transform.position = position;
522
523 if ( theAudioManager.verboseLogging ) {
524 Debug.Log( "[AudioManager] PlaySoundAt() channel = " + idx + " soundFX = " + soundFX.name + " volume = " + emitter.volume + " Delay = " + delay + " time = " + Time.time + "\n" );
525 }
526
527 // play the sound
528 if ( delay > 0f ) {
529 audioSource.PlayDelayed( delay );
530 } else {
531 audioSource.Play();
532 }
533
534 return idx;
535 }
536
537 /*
538 -----------------------
539 PlayRandomSoundAt()
540 -----------------------
541 */
542 static public int PlayRandomSoundAt( Vector3 position, AudioClip[] clips, float volume, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float pitch = 1.0f, bool loop = false ) {
543 if ( ( clips == null ) || ( clips.Length == 0 ) ) {
544 return -1;
545 }
546 int idx = Random.Range( 0, clips.Length );
547 return PlaySoundAt( position, clips[idx], volume, src, delay, pitch, loop );
548 }
549
550 /*
551 -----------------------
552 PlaySoundAt()
553 -----------------------
554 */
555 static public int PlaySoundAt( Vector3 position, AudioClip clip, float volume = 1.0f, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float pitch = 1.0f, bool loop = false ) {
556 if ( !SoundEnabled ) {
557 return -1;
558 }
559
560 if ( clip == null ) {
561 return -1;
562 }
563
564 // check the distance from the local player and ignore sounds out of range
565 if ( staticListenerPosition != null ) {
566 if ( ( staticListenerPosition.position - position ).sqrMagnitude > theAudioManager.audioMaxFallOffDistanceSqr ) {
567 // no chance of being heard
568 return -1;
569 }
570 }
571
572 int idx = FindFreeEmitter( src, 0 );
573 if ( idx == -1 ) {
574 // no free emitters - should only happen on very low priority sounds
575 return -1;
576 }
577 SoundEmitter emitter = theAudioManager.soundEmitters[idx];
578
579 // make sure to detach the emitter from a previous parent
580 emitter.ResetParent( soundEmitterParent.transform );
581 emitter.gameObject.SetActive( true );
582
583 // set up the sound emitter
584 AudioSource audioSource = emitter.audioSource;
585 ONSPAudioSource osp = emitter.osp;
586
587 audioSource.enabled = true;
588 audioSource.volume = Mathf.Clamp01( theAudioManager.volumeSoundFX * volume );
589 audioSource.pitch = pitch;
590 audioSource.spatialBlend = 0.8f;
591 audioSource.rolloffMode = AudioRolloffMode.Linear;
592 audioSource.SetCustomCurve( AudioSourceCurveType.ReverbZoneMix, defaultReverbZoneMix );
593 audioSource.dopplerLevel = 0.0f;
594 audioSource.clip = clip;
595 audioSource.spread = 0.0f;
596 audioSource.loop = loop;
597 audioSource.mute = false;
598 audioSource.minDistance = theAudioManager.audioMinFallOffDistance;
599 audioSource.maxDistance = theAudioManager.audioMaxFallOffDistance;
600 audioSource.outputAudioMixerGroup = AudioManager.EmitterGroup;
601 // set the play time so we can check when sounds are done
602 emitter.endPlayTime = Time.time + clip.length + delay;
603 // cache the default volume for fading
604 emitter.defaultVolume = audioSource.volume;
605 // default priority
606 emitter.priority = 0;
607 // reset this
608 emitter.onFinished = null;
609 // update the sound group limits
610 emitter.SetPlayingSoundGroup( null );
611 // add to the playing list
612 if ( src == EmitterChannel.Any ) {
613 theAudioManager.playingEmitters.AddUnique( emitter );
614 }
615
616 // disable spatialization (by default for regular AudioClips)
617 if ( osp != null ) {
618 osp.EnableSpatialization = false;
619 }
620
621 audioSource.transform.position = position;
622
623 if ( theAudioManager.verboseLogging ) {
624 Debug.Log( "[AudioManager] PlaySoundAt() channel = " + idx + " clip = " + clip.name + " volume = " + emitter.volume + " Delay = " + delay + " time = " + Time.time + "\n" );
625 }
626
627 // play the sound
628 if ( delay > 0f ) {
629 audioSource.PlayDelayed( delay );
630 } else {
631 audioSource.Play();
632 }
633
634 return idx;
635 }
636
637 /*
638 -----------------------
639 SetOnFinished()
640 -----------------------
641 */
642 public static void SetOnFinished( int emitterIdx, System.Action onFinished ) {
643 if ( emitterIdx >= 0 && emitterIdx < theAudioManager.maxSoundEmitters ) {
644 theAudioManager.soundEmitters[emitterIdx].SetOnFinished( onFinished );
645 }
646 }
647
648 /*
649 -----------------------
650 SetOnFinished()
651 -----------------------
652 */
653 public static void SetOnFinished( int emitterIdx, System.Action<object> onFinished, object obj ) {
654 if ( emitterIdx >= 0 && emitterIdx < theAudioManager.maxSoundEmitters ) {
655 theAudioManager.soundEmitters[emitterIdx].SetOnFinished( onFinished, obj );
656 }
657 }
658
659 /*
660 -----------------------
661 AttachSoundToParent()
662 -----------------------
663 */
664 public static void AttachSoundToParent( int idx, Transform parent ) {
665 if ( theAudioManager.verboseLogging ) {
666 string parentName = parent.name;
667 if ( parent.parent != null ) {
668 parentName = parent.parent.name + "/" + parentName;
669 }
670 Debug.Log( "[AudioManager] ATTACHING INDEX " + idx + " to " + parentName );
671 }
672 theAudioManager.soundEmitters[idx].ParentTo( parent );
673 }
674
675 /*
676 -----------------------
677 DetachSoundFromParent()
678 -----------------------
679 */
680 public static void DetachSoundFromParent( int idx ) {
681 if ( theAudioManager.verboseLogging ) {
682 Debug.Log( "[AudioManager] DETACHING INDEX " + idx );
683 }
684 theAudioManager.soundEmitters[idx].DetachFromParent();
685 }
686
687 /*
688 -----------------------
689 DetachSoundsFromParent()
690 -----------------------
691 */
692 public static void DetachSoundsFromParent( SoundEmitter[] emitters, bool stopSounds = true ) {
693 if ( emitters == null ) {
694 return;
695 }
696 foreach ( SoundEmitter emitter in emitters ) {
697 if ( emitter.defaultParent != null ) {
698 if ( stopSounds ) {
699 emitter.Stop();
700 }
701 emitter.DetachFromParent();
702 // make sure it's active
703 emitter.gameObject.SetActive( true );
704 } else {
705 if ( stopSounds ) {
706 emitter.Stop();
707 }
708 }
709 }
710 }
711
712 /*
713 -----------------------
714 SetEmitterMixerGroup()
715 -----------------------
716 */
717 public static void SetEmitterMixerGroup( int idx, AudioMixerGroup mixerGroup ) {
718 if ( ( theAudioManager != null ) && ( idx > -1 ) ) {
719 theAudioManager.soundEmitters[idx].SetAudioMixer( mixerGroup );
720 }
721 }
722
723 /*
724 -----------------------
725 GetActiveSnapshot()
726 -----------------------
727 */
728 public static MixerSnapshot GetActiveSnapshot() {
729 return ( theAudioManager != null ) ? theAudioManager.currentSnapshot : null;
730 }
731
732 /*
733 -----------------------
734 SetCurrentSnapshot()
735 -----------------------
736 */
737 public static void SetCurrentSnapshot( MixerSnapshot mixerSnapshot ) {
738#if UNITY_EDITOR
739 if ( mixerSnapshot == null || mixerSnapshot.snapshot == null ) {
740 Debug.LogError( "[AudioManager] ERROR setting empty mixer snapshot!" );
741 } else {
742 Debug.Log( "[AudioManager] Setting audio mixer snapshot: " + ( ( mixerSnapshot != null && mixerSnapshot.snapshot != null ) ? mixerSnapshot.snapshot.name : "None" ) + " Time: " + Time.time );
743 }
744#endif
745 if ( theAudioManager != null ) {
746 if ( ( mixerSnapshot != null ) && ( mixerSnapshot.snapshot != null ) ) {
747 mixerSnapshot.snapshot.TransitionTo( mixerSnapshot.transitionTime );
748 } else {
749 mixerSnapshot = null;
750 }
751 theAudioManager.currentSnapshot = mixerSnapshot;
752 }
753 }
754
755 /*
756 -----------------------
757 BlendWithCurrentSnapshot()
758 -----------------------
759 */
760 public static void BlendWithCurrentSnapshot( MixerSnapshot blendSnapshot, float weight, float blendTime = 0.0f ) {
761 if ( theAudioManager != null ) {
762 if ( theAudioManager.audioMixer == null ) {
763 Debug.LogWarning( "[AudioManager] can't call BlendWithCurrentSnapshot if the audio mixer is not set!" );
764 return;
765 }
766 if ( blendTime == 0.0f ) {
767 blendTime = Time.deltaTime;
768 }
769 if ( ( theAudioManager.currentSnapshot != null ) && (theAudioManager.currentSnapshot.snapshot != null ) ) {
770 if ( ( blendSnapshot != null ) && ( blendSnapshot.snapshot != null ) ) {
771 weight = Mathf.Clamp01( weight );
772 if ( weight == 0.0f ) {
773 // revert to the default snapshot
774 theAudioManager.currentSnapshot.snapshot.TransitionTo( blendTime );
775 } else {
776 AudioMixerSnapshot[] snapshots = new AudioMixerSnapshot[] { theAudioManager.currentSnapshot.snapshot, blendSnapshot.snapshot };
777 float[] weights = new float[] { 1.0f - weight, weight };
778 theAudioManager.audioMixer.TransitionToSnapshots( snapshots, weights, blendTime );
779 }
780 }
781 }
782 }
783 }
784
785}
786
787} // namespace OVR