/// <summary> /// 开始淡入播放下一首音乐。 /// - 如果正在淡出,则等淡出完成后再开始新的淡入。 /// - 如果正在淡入,则正在进行的淡入过程会被中断。 /// - 如果 fadeInDuration 为 null,则使用音乐自带的淡入时间参数。 /// - 目前没有处理上一首音乐正在正常播放的情况。 /// </summary> public static void Play(MusicParameters musicParams, float?fadeInDuration = null, bool loop = false) { if (Singleton == null) { return; } if (Singleton.isFadeOut) { Singleton.nextMusicParams = musicParams; Singleton.nextMusicIsLoop = loop; Singleton.isWaitForPlaying = true; Singleton.fadeInDuration = fadeInDuration; } else { if (Singleton.currentMusicParams != null && Singleton.currentMusicParams.Clip == musicParams.Clip) { return; } Singleton.currentMusicParams = musicParams; Singleton.audioSource.clip = musicParams.Clip; Singleton.audioSource.loop = loop; Singleton.audioSource.time = 0; Singleton.audioSource.Play(); Singleton.Volume = 0; Singleton.isFadeIn = true; Singleton.isWaitForPlaying = false; Singleton.nextMusicParams = null; Singleton.fadeInDuration = fadeInDuration; } }
private void Update() { if (isMute && muteFactor > Mathf.Epsilon) { float muteDuration = this.muteDuration.HasValue ? this.muteDuration.Value : currentMusicParams.FadeOutDuration; float fadeSpeed = 1 / muteDuration; muteFactor -= fadeSpeed * Time.deltaTime; if (muteFactor < 0) { muteFactor = 0; } UpdateVolume(); } else if (!isMute && muteFactor < 1) { float muteDuration = this.muteDuration.HasValue ? this.muteDuration.Value : currentMusicParams.FadeInDuration; float fadeSpeed = 1 / muteDuration; muteFactor += fadeSpeed * Time.deltaTime; if (muteFactor > 1) { muteFactor = 1; } UpdateVolume(); } if (isFadeIn) { float fadeInDuration = Singleton.fadeInDuration.HasValue ? Singleton.fadeInDuration.Value : currentMusicParams.FadeInDuration; float fadeSpeed = currentMusicParams.Volume / fadeInDuration; Volume += fadeSpeed * Time.deltaTime; if (Volume >= currentMusicParams.Volume) { Volume = currentMusicParams.Volume; isFadeIn = false; Singleton.fadeInDuration = null; } } else if (isFadeOut) { float fadeOutDuration = Singleton.fadeOutDuration.HasValue ? Singleton.fadeOutDuration.Value : currentMusicParams.FadeOutDuration; float fadeSpeed = currentMusicParams.Volume / fadeOutDuration; Volume -= fadeSpeed * Time.deltaTime; if (Volume <= 0) { Volume = 0; isFadeOut = false; audioSource.Stop(); currentMusicParams = null; Singleton.fadeOutDuration = null; if (isWaitForPlaying && nextMusicParams != null) { Play(nextMusicParams, Singleton.fadeInDuration, nextMusicIsLoop); } } } if (!isPlaying && IsPlaying && PlayStarted != null) { PlayStarted(); } else if (isPlaying && !IsPlaying && PlayEnded != null) { currentMusicParams = null; PlayEnded(); } isPlaying = IsPlaying; }
/// <summary> /// 淡入循环播放下一首音乐。 /// 如果 fadeInDuration 为 null,则使用音乐自带的淡入时间参数。 /// </summary> public static void Loop(MusicParameters musicParams, float?fadeInDuration = null) { Play(musicParams, fadeInDuration, true); }