89 lines
2.3 KiB
C#
89 lines
2.3 KiB
C#
|
using System.Collections;
|
||
|
using System.Collections.Generic;
|
||
|
using UnityEngine;
|
||
|
|
||
|
public class Wind : MonoBehaviour
|
||
|
{
|
||
|
public AudioSource windSound1;
|
||
|
public AudioSource windSound2;
|
||
|
public List<AudioClip> windSounds;
|
||
|
public float crossfadeDuration = 2f;
|
||
|
|
||
|
private bool source1 = true;
|
||
|
|
||
|
void Start()
|
||
|
{
|
||
|
// Ensure AudioSources are properly initialized
|
||
|
windSound1.volume = 1f;
|
||
|
windSound2.volume = 0f;
|
||
|
|
||
|
windSound1.clip = GetRandomClip();
|
||
|
windSound1.Play();
|
||
|
|
||
|
StartCoroutine(PlayWindSounds());
|
||
|
}
|
||
|
|
||
|
private IEnumerator PlayWindSounds()
|
||
|
{
|
||
|
while (true)
|
||
|
{
|
||
|
AudioSource activeSource = source1 ? windSound1 : windSound2;
|
||
|
AudioSource nextSource = source1 ? windSound2 : windSound1;
|
||
|
|
||
|
// Assign a new clip to the inactive source
|
||
|
nextSource.clip = GetRandomClip();
|
||
|
|
||
|
// Start playing the new clip
|
||
|
nextSource.Play();
|
||
|
|
||
|
// Start crossfade
|
||
|
StartCoroutine(Crossfade(activeSource, nextSource, crossfadeDuration));
|
||
|
|
||
|
// Wait until near the end of the active clip
|
||
|
print("--------");
|
||
|
print(nextSource.clip.name);
|
||
|
print(nextSource.clip.length);
|
||
|
print(crossfadeDuration);
|
||
|
print("--------");
|
||
|
|
||
|
yield return new WaitForSeconds(nextSource.clip.length - crossfadeDuration);
|
||
|
|
||
|
// Swap sources
|
||
|
source1 = !source1;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private IEnumerator Crossfade(AudioSource fromSource, AudioSource toSource, float duration)
|
||
|
{
|
||
|
float timer = 0f;
|
||
|
|
||
|
while (timer < duration)
|
||
|
{
|
||
|
timer += Time.deltaTime;
|
||
|
float t = timer / duration;
|
||
|
|
||
|
fromSource.volume = Mathf.Lerp(1f, 0f, t);
|
||
|
toSource.volume = Mathf.Lerp(0f, 1f, t);
|
||
|
|
||
|
yield return null;
|
||
|
}
|
||
|
|
||
|
fromSource.volume = 0f;
|
||
|
toSource.volume = 1f;
|
||
|
|
||
|
// Stop the source that is fully faded out
|
||
|
fromSource.Stop();
|
||
|
}
|
||
|
|
||
|
private AudioClip GetRandomClip()
|
||
|
{
|
||
|
if (windSounds.Count == 0)
|
||
|
{
|
||
|
Debug.LogError("No wind sounds available in the list!");
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
return windSounds[Random.Range(0, windSounds.Count)];
|
||
|
}
|
||
|
}
|