HeavenStudioPlus/Assets/Scripts/Util/Sound.cs

108 lines
2.7 KiB
C#
Raw Normal View History

2021-12-21 01:10:49 +00:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RhythmHeavenMania.Util
{
public class Sound : MonoBehaviour
{
public AudioClip clip;
2022-01-15 07:08:23 +00:00
public float pitch = 1;
public float volume = 1;
2021-12-21 01:10:49 +00:00
// For use with PlayOneShotScheduled
public bool scheduled;
public double scheduledTime;
2022-03-07 09:16:31 +00:00
public bool looping;
2021-12-21 01:10:49 +00:00
private AudioSource audioSource;
2022-01-15 07:08:23 +00:00
private int pauseTimes = 0;
private float startTime;
2022-01-21 01:24:30 +00:00
public float beat;
bool playInstant = false;
int playIndex = 0;
2021-12-21 01:10:49 +00:00
private void Start()
{
audioSource = GetComponent<AudioSource>();
2022-01-15 07:08:23 +00:00
audioSource.clip = clip;
audioSource.pitch = pitch;
audioSource.volume = volume;
2022-03-07 09:16:31 +00:00
audioSource.loop = looping;
if (beat == -1 && !scheduled)
2022-01-21 01:24:30 +00:00
{
audioSource.PlayScheduled(Time.time);
playInstant = true;
playIndex++;
}
else
{
2022-01-21 01:24:30 +00:00
playInstant = false;
}
2022-01-21 01:24:30 +00:00
startTime = Conductor.instance.songPosition;
2022-03-07 09:16:31 +00:00
if (!scheduled && !looping)
StartCoroutine(NotRelyOnBeatSound());
2021-12-21 01:10:49 +00:00
}
2022-01-15 07:08:23 +00:00
private void Update()
2021-12-21 01:10:49 +00:00
{
2022-03-07 09:16:31 +00:00
if (playIndex < 1)
{
2022-03-07 09:16:31 +00:00
if (scheduled)
{
2022-03-07 09:16:31 +00:00
if (AudioSettings.dspTime > scheduledTime)
{
StartCoroutine(NotRelyOnBeatSound());
playIndex++;
}
}
2022-03-07 09:16:31 +00:00
else if (!playInstant)
2022-01-20 01:48:52 +00:00
{
2022-03-07 09:16:31 +00:00
if (Conductor.instance.songPositionInBeats > beat)
{
audioSource.PlayScheduled(Time.time);
playIndex++;
}
2022-01-20 01:48:52 +00:00
}
2022-01-15 07:08:23 +00:00
}
}
2022-01-15 07:08:23 +00:00
IEnumerator NotRelyOnBeatSound()
{
2022-03-07 09:16:31 +00:00
if (!looping) // Looping sounds are destroyed manually.
{
yield return new WaitForSeconds(clip.length);
Destroy(this.gameObject);
}
}
public void KillLoop(float fadeTime)
{
StartCoroutine(FadeLoop(fadeTime));
}
float loopFadeTimer = 0f;
IEnumerator FadeLoop(float fadeTime)
{
float startingVol = audioSource.volume;
while (loopFadeTimer < fadeTime)
{
loopFadeTimer += Time.deltaTime;
audioSource.volume = Mathf.Max((1f - (loopFadeTimer / fadeTime)) * startingVol, 0f);
yield return null;
}
Destroy(this.gameObject);
2021-12-21 01:10:49 +00:00
}
}
}