//Create two audio sources to play audio. void Awake() { this.currentState = LoopedBGMState.Stopped; this.currentSource = this.gameObject.AddComponent <AudioSource>(); this.nextSource = this.gameObject.AddComponent <AudioSource>(); this.SetSong(this.songToPlay, this.loopSeconds); }
public override void Play() { this.currentState = LoopedBGMState.Playing; this.currentSourceVolume = 1; this.nextSourceVolume = 0; this.currentSource.Play(); }
//Check if the current source needs to be faded out. If so, start //playing next source, and transition! private void PlayingUpdate() { if (this.currentSource.time >= this.loopSeconds) { this.nextSource.Play(); this.currentState = LoopedBGMState.Transitioning; } }
//Every frame, make currentSource quieter, and nextSource louder. Once //currentSource is muted and nextSource is at full volume, stop currentSource //and swap them. private void TransitioningUpdate() { float dVolume = this.fadePerSecond * Time.deltaTime; this.currentSourceVolume = Mathf.Clamp(this.currentSourceVolume - dVolume, 0, 1); this.nextSourceVolume = Mathf.Clamp(this.nextSourceVolume + dVolume, 0, 1); if (this.currentSourceVolume == 0 && this.nextSourceVolume == 1) { this.currentSource.Stop(); //Swap them - t is just a temporary place to put one of them while swapping. AudioSource t = this.currentSource; this.currentSource = this.nextSource; this.nextSource = t; //Don't forget to switch the volume values, too! float v = this.currentSourceVolume; this.currentSourceVolume = this.nextSourceVolume; this.nextSourceVolume = v; this.currentState = LoopedBGMState.Playing; } }
public override void Stop() { this.currentState = LoopedBGMState.Stopped; this.currentSource.Stop(); this.nextSource.Stop(); }