AudioCore0.1
This commit is contained in:
64
Assets/04.AudioCore/RunTime/MusicPlayer.cs
Normal file
64
Assets/04.AudioCore/RunTime/MusicPlayer.cs
Normal file
@@ -0,0 +1,64 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user