71 lines
2.0 KiB
C#
71 lines
2.0 KiB
C#
|
|
using System.Collections;
|
|||
|
|
using UnityEngine;
|
|||
|
|
|
|||
|
|
public class VoicePlayer
|
|||
|
|
{
|
|||
|
|
private AudioSourcePool audioSourcePool;
|
|||
|
|
private AudioSource currentSource; // <20><>ǰ<EFBFBD><C7B0><EFBFBD>ڲ<EFBFBD><DAB2>ŵ<EFBFBD> AudioSource
|
|||
|
|
Coroutine myCoroutine;
|
|||
|
|
|
|||
|
|
public VoicePlayer(AudioSourcePool audioSourcePool)
|
|||
|
|
{
|
|||
|
|
this.audioSourcePool = audioSourcePool;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/*public override void Play(AudioClip clip, float volume = 1)
|
|||
|
|
{
|
|||
|
|
// ֹͣ<CDA3><D6B9>ǰ<EFBFBD><C7B0><EFBFBD>ڲ<EFBFBD><DAB2>ŵ<EFBFBD><C5B5><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
|
Stop();
|
|||
|
|
|
|||
|
|
currentSource = audioSourcePool.GetAudioSource("Voice");
|
|||
|
|
if (currentSource == null) return;
|
|||
|
|
|
|||
|
|
currentSource.clip = clip;
|
|||
|
|
currentSource.volume = volume;
|
|||
|
|
currentSource.Play();
|
|||
|
|
}
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
|
public void Play(AudioClip clip, float volume = 1f, System.Action onComplete = null, float delayOnComplete = 0f)
|
|||
|
|
{
|
|||
|
|
// ֹͣ<CDA3><D6B9>ǰ<EFBFBD><C7B0><EFBFBD>ڲ<EFBFBD><DAB2>ŵ<EFBFBD><C5B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Э<EFBFBD><D0AD>
|
|||
|
|
Stop();
|
|||
|
|
if(myCoroutine!= null)
|
|||
|
|
{
|
|||
|
|
CoroutineHelper.StopCoroutine(myCoroutine);
|
|||
|
|
myCoroutine = null;
|
|||
|
|
}
|
|||
|
|
currentSource = audioSourcePool.GetAudioSource("Voice");
|
|||
|
|
if (currentSource == null) return;
|
|||
|
|
|
|||
|
|
currentSource.clip = clip;
|
|||
|
|
currentSource.volume = volume;
|
|||
|
|
currentSource.Play();
|
|||
|
|
|
|||
|
|
// ʹ<><CAB9>Э<EFBFBD>̴<EFBFBD><CCB4><EFBFBD><EFBFBD>ӳٺͻص<CDBB>
|
|||
|
|
myCoroutine = CoroutineHelper.StartCoroutine(PlayVoiceCoroutine(currentSource, delayOnComplete, onComplete));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ֹͣ<CDA3><D6B9><EFBFBD><EFBFBD>
|
|||
|
|
public void Stop()
|
|||
|
|
{
|
|||
|
|
if (currentSource != null && currentSource.isPlaying)
|
|||
|
|
{
|
|||
|
|
currentSource.Stop();
|
|||
|
|
audioSourcePool.ReturnAudioSource("Voice", currentSource.gameObject);
|
|||
|
|
currentSource = null;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Э<EFBFBD><D0AD>
|
|||
|
|
private IEnumerator PlayVoiceCoroutine(AudioSource source, float delayOnComplete, System.Action onComplete)
|
|||
|
|
{
|
|||
|
|
yield return new WaitForSeconds(source.clip.length+delayOnComplete);
|
|||
|
|
|
|||
|
|
onComplete?.Invoke();
|
|||
|
|
audioSourcePool.ReturnAudioSource("Voice", source.gameObject);
|
|||
|
|
currentSource = null;
|
|||
|
|
myCoroutine = null;
|
|||
|
|
}
|
|||
|
|
}
|