AudioCore0.1
This commit is contained in:
71
Assets/04.AudioCore/RunTime/VoicePlayer.cs
Normal file
71
Assets/04.AudioCore/RunTime/VoicePlayer.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
public class VoicePlayer
|
||||
{
|
||||
private AudioSourcePool audioSourcePool;
|
||||
private AudioSource currentSource; // 当前正在播放的 AudioSource
|
||||
Coroutine myCoroutine;
|
||||
|
||||
public VoicePlayer(AudioSourcePool audioSourcePool)
|
||||
{
|
||||
this.audioSourcePool = audioSourcePool;
|
||||
}
|
||||
|
||||
/*public override void Play(AudioClip clip, float volume = 1)
|
||||
{
|
||||
// 停止当前正在播放的语音
|
||||
Stop();
|
||||
|
||||
currentSource = audioSourcePool.GetAudioSource("Voice");
|
||||
if (currentSource == null) return;
|
||||
|
||||
currentSource.clip = clip;
|
||||
currentSource.volume = volume;
|
||||
currentSource.Play();
|
||||
}
|
||||
*/
|
||||
|
||||
// 播放语音
|
||||
public void Play(AudioClip clip, float volume = 1f, System.Action onComplete = null, float delayOnComplete = 0f)
|
||||
{
|
||||
// 停止当前正在播放的语音与旧协程
|
||||
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();
|
||||
|
||||
// 使用协程处理延迟和回调
|
||||
myCoroutine = CoroutineHelper.StartCoroutine(PlayVoiceCoroutine(currentSource, delayOnComplete, onComplete));
|
||||
}
|
||||
|
||||
// 停止语音
|
||||
public void Stop()
|
||||
{
|
||||
if (currentSource != null && currentSource.isPlaying)
|
||||
{
|
||||
currentSource.Stop();
|
||||
audioSourcePool.ReturnAudioSource("Voice", currentSource.gameObject);
|
||||
currentSource = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 播放语音的协程
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user