SoundEmitter.cs 10.2 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 430 431 432 433
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;

namespace OVR
{

/*
-----------------------
 
 SoundEmitter()
 
-----------------------
*/
public class SoundEmitter : MonoBehaviour {
	public enum FadeState {
		Null,
		FadingIn,
		FadingOut,
		Ducking,
	}	

	// OPTIMIZE

	public float 					volume { get { return audioSource.volume; } set { audioSource.volume = value; } }
	public float 					pitch { get { return audioSource.pitch; } set { audioSource.pitch = value; } }
	public AudioClip				clip { get { return audioSource.clip; } set { audioSource.clip = value; } }
	public float 					time { get { return audioSource.time; } set { audioSource.time = value; } }
	public float 					length { get { return ( audioSource.clip != null ) ? audioSource.clip.length : 0.0f; } }
	public bool 					loop { get { return audioSource.loop; } set { audioSource.loop = value; } }
	public bool 					mute { get { return audioSource.mute; } set { audioSource.mute = value; } }
	public AudioVelocityUpdateMode	velocityUpdateMode { get { return audioSource.velocityUpdateMode; } set { audioSource.velocityUpdateMode = value; } }
	public bool						isPlaying { get { return audioSource.isPlaying; } }

	public EmitterChannel			channel = EmitterChannel.Reserved;
	public bool						disableSpatialization = false;
	private	FadeState				state = FadeState.Null;
	[System.NonSerialized]
	[HideInInspector]
	public AudioSource				audioSource = null;
	[System.NonSerialized]
	[HideInInspector]
	public SoundPriority            priority = SoundPriority.Default;
	[System.NonSerialized]
	[HideInInspector]
	public ONSPAudioSource			osp = null;
	[System.NonSerialized]
	[HideInInspector]
	public float					endPlayTime = 0.0f;
	private Transform				lastParentTransform = null;
	[System.NonSerialized]
	[HideInInspector]
	public float					defaultVolume = 1.0f;
	[System.NonSerialized]
	[HideInInspector]
	public Transform				defaultParent = null;
	[System.NonSerialized]
	[HideInInspector]
	public int						originalIdx = -1;
	[System.NonSerialized]
	[HideInInspector]
	public System.Action			onFinished = null;
	[System.NonSerialized]
	[HideInInspector]
	public System.Action<object>	onFinishedObject = null;
	[System.NonSerialized]
	[HideInInspector]
	public object					onFinishedParam;
	[System.NonSerialized]
	[HideInInspector]
	public SoundGroup               playingSoundGroup = null;

	/*
	-----------------------
	Awake()
	-----------------------
	*/
	void Awake() {
		// unity defaults to 'playOnAwake = true'
		audioSource = GetComponent<AudioSource>();
		if ( audioSource == null ) {
			audioSource = gameObject.AddComponent<AudioSource>();
		}
		// is the spatialized audio enabled?
		if ( AudioManager.enableSpatialization && !disableSpatialization ) {
			osp = GetComponent<ONSPAudioSource>(); 
			if ( osp == null ) {
				osp = gameObject.AddComponent<ONSPAudioSource>();
			}
		}
		audioSource.playOnAwake = false;
		audioSource.Stop();
	}

	/*
	-----------------------
	SetPlayingSoundGroup()
	-----------------------
	*/
	public void SetPlayingSoundGroup( SoundGroup soundGroup ) {
		playingSoundGroup = soundGroup;
		if ( soundGroup != null ) {
			soundGroup.IncrementPlayCount();
		}
	}

	/*
	-----------------------
	SetOnFinished()
	-----------------------
	*/
	public void SetOnFinished( System.Action onFinished ) {
		this.onFinished = onFinished;
	}

	/*
	-----------------------
	SetOnFinished()
	-----------------------
	*/
	public void SetOnFinished( System.Action<object> onFinished, object obj ) {
		onFinishedObject = onFinished;
		onFinishedParam = obj;
	}

	/*
	-----------------------
	SetChannel()
	-----------------------
	*/
	public void SetChannel( int _channel ) {
		channel = (EmitterChannel)_channel;
	}

	/*
	-----------------------
	SetDefaultParent()
	-----------------------
	*/
	public void SetDefaultParent( Transform parent ) {
		defaultParent = parent;
	}

	/*
	-----------------------
	SetAudioMixer()
	-----------------------
	*/
	public void SetAudioMixer( AudioMixerGroup _mixer ) {
		if ( audioSource != null ) {
			audioSource.outputAudioMixerGroup = _mixer;
		}
	}

	/*
	-----------------------
	IsPlaying()
	-----------------------
	*/
	public bool IsPlaying() {
		if ( loop && audioSource.isPlaying ) {
			return true;
		}
		return endPlayTime > Time.time;
	} 

	/*
	-----------------------
	Play()
	-----------------------
	*/
	public void Play() {
		// overrides everything
		state = FadeState.Null;
		endPlayTime = Time.time + length;
		StopAllCoroutines();
		audioSource.Play();
	}

	/*
	-----------------------
	Pause()
	-----------------------
	*/
	public void Pause() {
		// overrides everything
		state = FadeState.Null;
		StopAllCoroutines();
		audioSource.Pause();
	}
	
	/*
	-----------------------
	Stop()
	-----------------------
	*/
	public void Stop() {
		// overrides everything
		state = FadeState.Null;
		StopAllCoroutines();
		if ( audioSource != null ) {
			audioSource.Stop();
		}
		if ( onFinished != null ) {
			onFinished();
			onFinished = null;
		}
		if ( onFinishedObject != null ) {
			onFinishedObject( onFinishedParam );
			onFinishedObject = null;
		}
		if ( playingSoundGroup != null ) {
			playingSoundGroup.DecrementPlayCount();
			playingSoundGroup = null;
		}
	}

	/*
	-----------------------
	GetSampleTime()
	-----------------------
	*/
	int GetSampleTime() {
		return audioSource.clip.samples - audioSource.timeSamples;
	}

	/*
	-----------------------
	ParentTo()
	-----------------------
	*/
	public void ParentTo( Transform parent ) {
		if ( lastParentTransform != null ) {
			Debug.LogError( "[SoundEmitter] You must detach the sound emitter before parenting to another object!" );
			return;
		}
		lastParentTransform = transform.parent;
		transform.parent = parent;
	}

	/*
	-----------------------
	DetachFromParent()
	-----------------------
	*/
	public void DetachFromParent() {
		if ( lastParentTransform == null ) {
			transform.parent = defaultParent;
			return;
		}
		transform.parent = lastParentTransform;
		lastParentTransform = null;
	}

	/*
	-----------------------
	ResetParent()
	-----------------------
	*/
	public void ResetParent( Transform parent ) {
		transform.parent = parent;
		lastParentTransform = null;
	}

	/*
	-----------------------
	SyncTo()
	-----------------------
	*/
	public void SyncTo( SoundEmitter other, float fadeTime, float toVolume ) {
		StartCoroutine( DelayedSyncTo( other, fadeTime, toVolume ) );
	}

	/*
	-----------------------
	DelayedSyncTo()
	have to wait until the end of frame to do proper sync'ing
	-----------------------
	*/
	IEnumerator DelayedSyncTo( SoundEmitter other, float fadeTime, float toVolume ) {
		yield return new WaitForEndOfFrame();
		//audio.timeSamples = other.GetSampleTime();
		//audio.time = Mathf.Min( Mathf.Max( 0.0f, other.time - other.length ), other.time );
		audioSource.time = other.time;
		audioSource.Play();
		FadeTo( fadeTime, toVolume );
	}

	/*
	-----------------------
	FadeTo()
	-----------------------
	*/
	public void FadeTo( float fadeTime, float toVolume ) {
		//Log.Print( ">>> FADE TO: " + channel );

		
		// don't override a fade out 
		if ( state == FadeState.FadingOut ) {
			//Log.Print( "    ....ABORTED" );
			return; 
		}
		state = FadeState.Ducking;
		StopAllCoroutines();
		StartCoroutine( FadeSoundChannelTo( fadeTime, toVolume ) );
	}
	
	/*
	-----------------------
	FadeIn()
	-----------------------
	*/
	public void FadeIn( float fadeTime, float defaultVolume ) {
		
		//Log.Print( ">>> FADE IN: " + channel );
		audioSource.volume = 0.0f;		
		state = FadeState.FadingIn;		
		StopAllCoroutines();
		StartCoroutine( FadeSoundChannel( 0.0f, fadeTime, Fade.In, defaultVolume ) );
	}

	/*
	-----------------------
	FadeIn()
	-----------------------
	*/
	public void FadeIn( float fadeTime ) {

		//Log.Print( ">>> FADE IN: " + channel );
		audioSource.volume = 0.0f;
		state = FadeState.FadingIn;
		StopAllCoroutines();
		StartCoroutine( FadeSoundChannel( 0.0f, fadeTime, Fade.In, defaultVolume ) );
	}

	/*
	-----------------------
	FadeOut()
	-----------------------
	*/
	public void FadeOut( float fadeTime ) {
		//Log.Print( ">>> FADE OUT: " + channel );
		if ( !audioSource.isPlaying ) {
			//Log.Print( "   ... SKIPPING" );
			return;
		}
		state = FadeState.FadingOut;
		StopAllCoroutines();
		StartCoroutine( FadeSoundChannel( 0.0f, fadeTime, Fade.Out, audioSource.volume ) );
	}
	
	/*
	-----------------------
	FadeOutDelayed()
	-----------------------
	*/
	public void FadeOutDelayed( float delayedSecs, float fadeTime ) {
		//Log.Print( ">>> FADE OUT DELAYED: " + channel );
		if ( !audioSource.isPlaying ) {
			//Log.Print( "   ... SKIPPING" );
			return;
		}
		state = FadeState.FadingOut;
		StopAllCoroutines();
		StartCoroutine( FadeSoundChannel( delayedSecs, fadeTime, Fade.Out, audioSource.volume ) );
	}
	
	/*
	-----------------------
	FadeSoundChannelTo()
	-----------------------
	*/
	IEnumerator FadeSoundChannelTo( float fadeTime, float toVolume ) {
		float start = audioSource.volume;
		float end = toVolume;
		float startTime = Time.realtimeSinceStartup;
		float elapsedTime = 0.0f;

		while ( elapsedTime < fadeTime ) {
			elapsedTime = Time.realtimeSinceStartup - startTime;
			float t = elapsedTime / fadeTime;
			audioSource.volume = Mathf.Lerp( start, end, t );
			yield return 0;
		}
		state = FadeState.Null;
	}		
	
	/*
	-----------------------
	FadeSoundChannel()
	-----------------------
	*/
	IEnumerator FadeSoundChannel( float delaySecs, float fadeTime, Fade fadeType, float defaultVolume ) {
 		if ( delaySecs > 0.0f ) {
 			yield return new WaitForSeconds( delaySecs );
 		}
		float start = ( fadeType == Fade.In ) ? 0.0f : defaultVolume;
		float end = ( fadeType == Fade.In ) ? defaultVolume : 0.0f;
		bool restartPlay = false;
		
		if ( fadeType == Fade.In ) {
			if ( Time.time == 0.0f ) {
				restartPlay = true;
			}
			audioSource.volume = 0.0f;
			audioSource.Play();	
		}

		float startTime = Time.realtimeSinceStartup;
		float elapsedTime = 0.0f;

		while ( elapsedTime < fadeTime ) {
			elapsedTime = Time.realtimeSinceStartup - startTime;
			float t = elapsedTime / fadeTime;
			audioSource.volume = Mathf.Lerp( start, end, t );
			yield return 0;
			if ( restartPlay && ( Time.time > 0.0f ) ) {
				audioSource.Play();	
				restartPlay = false;
			}
			if ( !audioSource.isPlaying ) {
				break;
			}
		}

		if ( fadeType == Fade.Out ) {
			Stop();
		}
		state = FadeState.Null;
	}		
}

} // namespace OVR