AudioManager.cs 12.7 KB
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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
using System;
using System.Reflection;
#endif

namespace OVR
{

public enum PreloadSounds {
	Default,		// default unity behavior
	Preload,		// audio clips are forced to preload
	ManualPreload,	// audio clips are forced to not preload, preloading must be done manually
}

public enum Fade
{
    In,
    Out
}

[System.Serializable]
public class SoundGroup {
	public SoundGroup( string name ) {
		this.name = name;
	}
	public SoundGroup() {
		mixerGroup = null;
		maxPlayingSounds = 0;
		preloadAudio = PreloadSounds.Default;
		volumeOverride = 1.0f;
	}
	public void IncrementPlayCount() {
		playingSoundCount = Mathf.Clamp( ++playingSoundCount, 0, maxPlayingSounds );
	}
	public void DecrementPlayCount() {
		playingSoundCount = Mathf.Clamp( --playingSoundCount, 0, maxPlayingSounds );
	}
	public bool CanPlaySound() {
		return ( maxPlayingSounds == 0 ) || ( playingSoundCount < maxPlayingSounds );
	}

	public string			name = string.Empty;
	public SoundFX[]		soundList = new SoundFX[0];
	public AudioMixerGroup  mixerGroup = null;						// default = AudioManager.defaultMixerGroup
	[Range(0,64)]
	public int              maxPlayingSounds = 0;                   // default = 0, unlimited
	// TODO: this preload behavior is not yet implemented
	public PreloadSounds	preloadAudio = PreloadSounds.Default;	// default = true, audio clip data will be preloaded
	public float            volumeOverride = 1.0f;					// default = 1.0

	[HideInInspector]
	public int              playingSoundCount = 0;
}

/*
-----------------------

 AudioManager

-----------------------
*/
public partial class AudioManager : MonoBehaviour {

	[Tooltip("Make the audio manager persistent across all scene loads")]
	public bool							makePersistent = true;							// true = don't destroy on load
	[Tooltip("Enable the OSP audio plugin features")]
	public bool							enableSpatializedAudio = true;                  // true = enable spatialized audio
	[Tooltip("Always play spatialized sounds with no reflections (Default)")]
	public bool                         enableSpatializedFastOverride = false;          // true = disable spatialized reflections override
	[Tooltip("The audio mixer asset used for snapshot blends, etc.")]
	public AudioMixer                   audioMixer = null;
	[Tooltip( "The audio mixer group used for the pooled emitters" )]
	public AudioMixerGroup				defaultMixerGroup = null;
	[Tooltip( "The audio mixer group used for the reserved pool emitter" )]
	public AudioMixerGroup				reservedMixerGroup = null;
	[Tooltip( "The audio mixer group used for voice chat" )]
	public AudioMixerGroup				voiceChatMixerGroup = null;
	[Tooltip("Log all PlaySound calls to the Unity console")]
	public bool							verboseLogging = false;							// true = log all PlaySounds
	[Tooltip("Maximum sound emitters")]
	public int 							maxSoundEmitters = 32;							// total number of sound emitters created
	[Tooltip("Default volume for all sounds modulated by individual sound FX volumes")]
	public float						volumeSoundFX = 1.0f;							// user pref: volume of all sound FX
	[Tooltip("Sound FX fade time")]
	public float						soundFxFadeSecs = 1.0f;							// sound FX fade time
	
	public float						audioMinFallOffDistance = 1.0f;					// minimum falloff distance
	public float						audioMaxFallOffDistance = 25.0f;				// maximum falloff distance

	public SoundGroup[]					soundGroupings = new SoundGroup[0];

	private Dictionary<string,SoundFX>	soundFXCache = null;

	static private AudioManager			theAudioManager = null;
	static private FastList<string> 	names = new FastList<string>();
	static private string[]				defaultSound = new string[1] { "Default Sound" };
	static private SoundFX				nullSound = new SoundFX();
	static private bool					hideWarnings = false;
	static public bool 					enableSpatialization { get { return ( theAudioManager !=null ) ? theAudioManager.enableSpatializedAudio : false; } }

	static public AudioManager			Instance { get { return theAudioManager; } }
	static public float					NearFallOff { get { return theAudioManager.audioMinFallOffDistance; } }
	static public float					FarFallOff { get { return theAudioManager.audioMaxFallOffDistance; } }
	static public AudioMixerGroup		EmitterGroup { get { return theAudioManager.defaultMixerGroup; } }
	static public AudioMixerGroup		ReservedGroup { get { return theAudioManager.reservedMixerGroup; } }
	static public AudioMixerGroup		VoipGroup { get { return theAudioManager.voiceChatMixerGroup; } }

	/*
	-----------------------
	Awake()
	-----------------------
	*/
	void Awake() {
		Init();
	}

	/*
	-----------------------
	OnDestroy()
	-----------------------
	*/
	void OnDestroy() {
		// we only want the initialized audio manager instance cleaning up the sound emitters
		if ( theAudioManager == this ) {
			if ( soundEmitterParent != null ) {
				Destroy( soundEmitterParent );
			}
		}
		///TODO - if you change scenes you'll want to call OnPreSceneLoad to detach the sound emitters
		///from anything they might be parented to or they will get destroyed with that object
		///there should only be one instance of the AudioManager across the life of the game/app
		///GameManager.OnPreSceneLoad -= OnPreSceneLoad;
	}

	/*
	-----------------------
	Init()
	-----------------------
	*/
	void Init() {
		if ( theAudioManager != null ) {
			if ( Application.isPlaying && ( theAudioManager != this ) ) {
				enabled = false;
			}
			return;
		}
		theAudioManager = this;

		///TODO - if you change scenes you'll want to call OnPreSceneLoad to detach the sound emitters
		///from anything they might be parented to or they will get destroyed with that object
		///there should only be one instance of the AudioManager across the life of the game/app
		///GameManager.OnPreSceneLoad += OnPreSceneLoad;

		// make sure the first one is a null sound
		nullSound.name = "Default Sound";

		// build the sound FX cache
		RebuildSoundFXCache();

		// create the sound emitters
		if ( Application.isPlaying ) {
			InitializeSoundSystem();
			if ( makePersistent && ( transform.parent == null ) ) {
				// don't destroy the audio manager on scene loads
				DontDestroyOnLoad( gameObject );
			}
		}

#if UNITY_EDITOR
		Debug.Log( "[AudioManager] Initialized..." );
#endif
	}

	/*
	-----------------------
	Update()
	-----------------------
	*/
	void Update() {
		// update the free and playing lists
		UpdateFreeEmitters();
	}

	/*
	-----------------------
	RebuildSoundFXCache()
	-----------------------
	*/
	void RebuildSoundFXCache() {
		// build the SoundFX dictionary for quick name lookups
		int count = 0;
		for ( int group = 0; group < soundGroupings.Length; group++ ) {
			count += soundGroupings[group].soundList.Length;
		}
		soundFXCache = new Dictionary<string,SoundFX>( count + 1 );	
		// add the null sound
		soundFXCache.Add( nullSound.name, nullSound );
		// add the rest
		for ( int group = 0; group < soundGroupings.Length; group++ ) {
			for ( int i = 0; i < soundGroupings[group].soundList.Length; i++ ) {
				if ( soundFXCache.ContainsKey( soundGroupings[group].soundList[i].name ) ) {
					Debug.LogError( "ERROR: Duplicate Sound FX name in the audio manager: '" + soundGroupings[group].name + "' > '" + soundGroupings[group].soundList[i].name + "'" );
				} else {
					soundGroupings[group].soundList[i].Group = soundGroupings[group];
					soundFXCache.Add( soundGroupings[group].soundList[i].name, soundGroupings[group].soundList[i] );
				}
			}
			soundGroupings[group].playingSoundCount = 0;
		}
	}

	/*
	-----------------------
	FindSoundFX()
	-----------------------
	*/
	static public SoundFX FindSoundFX( string name, bool rebuildCache = false ) {
#if UNITY_EDITOR
		if ( theAudioManager == null ) {
			Debug.LogError( "ERROR: audio manager not yet initialized or created!" + " Time: " + Time.time  );
			return null;
		}
#endif
		if ( string.IsNullOrEmpty( name ) ) {
			return nullSound;
		}
		if ( rebuildCache ) {
			theAudioManager.RebuildSoundFXCache();
		}
		if ( !theAudioManager.soundFXCache.ContainsKey( name ) ) {
#if DEBUG_BUILD || UNITY_EDITOR
			Debug.LogError( "WARNING: Missing Sound FX in cache: " + name );
#endif
			return nullSound;
		}
		return theAudioManager.soundFXCache[name];
	}

	/*
	-----------------------
	FindAudioManager()
	-----------------------
	*/
	static private bool FindAudioManager() {
		GameObject audioManagerObject = GameObject.Find( "AudioManager" );
		if ( ( audioManagerObject == null ) || ( audioManagerObject.GetComponent<AudioManager>() == null ) ) {
			if ( !hideWarnings ) {
				Debug.LogError( "[ERROR] AudioManager object missing from hierarchy!" );
				hideWarnings = true;
			}
			return false;
		} else {
			audioManagerObject.GetComponent<AudioManager>().Init();
		}
		return true;
	}

	/*
	-----------------------
	GetGameObject()
	-----------------------
	*/
	static public GameObject GetGameObject() {
		if ( theAudioManager == null ) {
			if ( !FindAudioManager() ) {
				return null;
			}
		}
		return theAudioManager.gameObject;
	}

	/*
	-----------------------
	NameMinusGroup()
	strip off the sound group from the inspector dropdown
	-----------------------
	*/
	static public string NameMinusGroup( string name ) {
		if ( name.IndexOf( "/" ) > -1 ) {
			return name.Substring( name.IndexOf( "/" ) + 1 );
		}
		return name;
	}
	
	/*
	-----------------------
	GetSoundFXNames()
	used by the inspector
	-----------------------
	*/
	static public string[] GetSoundFXNames( string currentValue, out int currentIdx ) {
		currentIdx = 0;
		names.Clear();
		if ( theAudioManager == null ) {
			if ( !FindAudioManager() ) {
				return defaultSound;
			}
		}
		names.Add( nullSound.name );
		for ( int group = 0; group < theAudioManager.soundGroupings.Length; group++ ) {
			for ( int i = 0; i < theAudioManager.soundGroupings[group].soundList.Length; i++ ) {
				if ( string.Compare( currentValue, theAudioManager.soundGroupings[group].soundList[i].name, true ) == 0 ) {
					currentIdx = names.Count;
				}
				names.Add( theAudioManager.soundGroupings[group].name + "/" + theAudioManager.soundGroupings[group].soundList[i].name );
			}
		}
		//names.Sort( delegate( string s1, string s2 ) { return s1.CompareTo( s2 ); } );
		return names.ToArray();

	}
#if UNITY_EDITOR
	/*
	-----------------------
	OnPrefabReimported()
	-----------------------
	*/
	static public void OnPrefabReimported() {
		if ( theAudioManager != null ) {
			Debug.Log( "[AudioManager] Reimporting the sound FX cache." );
			theAudioManager.RebuildSoundFXCache();
		}
	}

	/*
	-----------------------
	PlaySound()
	used in the editor
	-----------------------
	*/
	static public void PlaySound( string soundFxName ) {
		if ( theAudioManager == null ) {
			if ( !FindAudioManager() ) {
				return;
			}
		}
		SoundFX soundFX = FindSoundFX( soundFxName, true );
		if ( soundFX == null ) {
			return;
		}
		AudioClip clip = soundFX.GetClip();
		if ( clip != null ) {
			Assembly unityEditorAssembly = typeof(AudioImporter).Assembly;
			Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
			MethodInfo method = audioUtilClass.GetMethod(
				"PlayClip",
				BindingFlags.Static | BindingFlags.Public,
				null,
				new System.Type[] { typeof(AudioClip) },
				null );
			method.Invoke( null, new object[] { clip } );
		}
	}

	/*
	-----------------------
	IsSoundPlaying()
	used in the editor
	-----------------------
	*/
	static public bool IsSoundPlaying( string soundFxName ) {
		if ( theAudioManager == null ) {
			if ( !FindAudioManager() ) {
				return false;
			}
		}
		SoundFX soundFX = FindSoundFX( soundFxName, true );
		if ( soundFX == null ) {
			return false;
		}
		AudioClip clip = soundFX.GetClip();
		if ( clip != null ) {
			Assembly unityEditorAssembly = typeof(AudioImporter).Assembly;
			Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
			MethodInfo method = audioUtilClass.GetMethod(
				"IsClipPlaying",
				BindingFlags.Static | BindingFlags.Public,
				null,
				new System.Type[] { typeof(AudioClip) },
				null );
			return Convert.ToBoolean( method.Invoke( null, new object[] { clip } ) );
		}

		return false;
	}

	/*
	-----------------------
	StopSound()
	used in the editor
	-----------------------
	*/
	static public void StopSound(string soundFxName)
	{
		if (theAudioManager == null)
		{
			if (!FindAudioManager())
			{
				return;
			}
		}
		SoundFX soundFX = FindSoundFX(soundFxName, true);
		if (soundFX == null)
		{
			return;
		}
		AudioClip clip = soundFX.GetClip();
		if (clip != null)
		{
			Assembly unityEditorAssembly = typeof(AudioImporter).Assembly;
			Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
			MethodInfo method = audioUtilClass.GetMethod(
				"StopClip",
				BindingFlags.Static | BindingFlags.Public,
				null,
				new System.Type[] { typeof(AudioClip) },
				null);
			method.Invoke(null, new object[] { clip });
		}
	}
#endif
}

} // namespace OVR