64 lines
1.6 KiB
C#
64 lines
1.6 KiB
C#
|
|
using System.Collections;
|
||
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
public class MusicPlayer
|
||
|
|
{
|
||
|
|
private AudioSourcePool audioSourcePool;
|
||
|
|
|
||
|
|
public MusicPlayer(AudioSourcePool audioSourcePool)
|
||
|
|
{
|
||
|
|
this.audioSourcePool = audioSourcePool;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Play(AudioClip clip, float fadeDuration)
|
||
|
|
{
|
||
|
|
AudioSource source = audioSourcePool.GetAudioSource("Music");
|
||
|
|
if (source == null) return;
|
||
|
|
|
||
|
|
CoroutineHelper.StartCoroutine(FadeMusic(source, clip, fadeDuration));
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Stop(float fadeDuration)
|
||
|
|
{
|
||
|
|
AudioSource source = audioSourcePool.GetAudioSource("Music");
|
||
|
|
if (source == null) return;
|
||
|
|
|
||
|
|
CoroutineHelper.StartCoroutine(FadeOutMusic(source, fadeDuration));
|
||
|
|
}
|
||
|
|
|
||
|
|
private IEnumerator FadeMusic(AudioSource source, AudioClip clip, float fadeDuration)
|
||
|
|
{
|
||
|
|
yield return FadeOutMusic(source, fadeDuration);
|
||
|
|
|
||
|
|
source.clip = clip;
|
||
|
|
source.Play();
|
||
|
|
|
||
|
|
yield return FadeInMusic(source, fadeDuration);
|
||
|
|
}
|
||
|
|
|
||
|
|
private IEnumerator FadeOutMusic(AudioSource source, float fadeDuration)
|
||
|
|
{
|
||
|
|
float startVolume = source.volume;
|
||
|
|
|
||
|
|
while (source.volume > 0)
|
||
|
|
{
|
||
|
|
source.volume -= startVolume * Time.deltaTime / fadeDuration;
|
||
|
|
yield return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
source.Stop();
|
||
|
|
source.volume = startVolume;
|
||
|
|
}
|
||
|
|
|
||
|
|
private IEnumerator FadeInMusic(AudioSource source, float fadeDuration)
|
||
|
|
{
|
||
|
|
float targetVolume = source.volume;
|
||
|
|
source.volume = 0;
|
||
|
|
|
||
|
|
while (source.volume < targetVolume)
|
||
|
|
{
|
||
|
|
source.volume += targetVolume * Time.deltaTime / fadeDuration;
|
||
|
|
yield return null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|