音频播放工具1.0.1
This commit is contained in:
76
Assets/04.AudioCore/RunTime/Base/VoicePlayer.cs
Normal file
76
Assets/04.AudioCore/RunTime/Base/VoicePlayer.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Stary.Evo.AudioCore
|
||||
{
|
||||
public class VoicePlayer : AbstractAudio
|
||||
{
|
||||
private AudioSourcePool audioSourcePool;
|
||||
private AudioSource currentSource;
|
||||
private Coroutine myCoroutine;
|
||||
|
||||
public VoicePlayer(AudioSourcePool audioSourcePool)
|
||||
{
|
||||
this.audioSourcePool = audioSourcePool;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 播放语音
|
||||
/// </summary>
|
||||
/// <param name="audioData">{[clip:音频], [volume:音量],
|
||||
/// [onComplete:回调行为], [delayOnCompleteTime:延迟回调执行的时间]}</param>
|
||||
public override void Play(AudioData audioData)
|
||||
{
|
||||
// 停止当前正在播放的语音与旧协程
|
||||
Stop(new AudioData { });
|
||||
|
||||
audioData = AudioDataInitialize(audioData);
|
||||
|
||||
if (myCoroutine != null)
|
||||
{
|
||||
CoroutineHelper.StopCoroutine(myCoroutine);
|
||||
myCoroutine = null;
|
||||
}
|
||||
currentSource = audioSourcePool.GetAudioSource("Voice");
|
||||
if (currentSource == null) return;
|
||||
|
||||
currentSource.clip = audioData.clip;
|
||||
currentSource.volume = audioData.volume;
|
||||
currentSource.Play();
|
||||
|
||||
// 使用协程处理延迟和回调
|
||||
myCoroutine = CoroutineHelper.StartCoroutine(PlayVoiceCoroutine(currentSource, audioData.delayOnCompleteTime, audioData.onComplete));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止语音
|
||||
/// </summary>
|
||||
/// /// <param name="audioData">{[无可使用变量]}</param>
|
||||
public override void Stop(AudioData audioData)
|
||||
{
|
||||
if (currentSource != null && currentSource.isPlaying)
|
||||
{
|
||||
currentSource.Stop();
|
||||
audioSourcePool.ReturnAudioSource("Voice", currentSource.gameObject);
|
||||
currentSource = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 播放语音的协程
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="delayOnComplete"></param>
|
||||
/// <param name="onComplete"></param>
|
||||
/// <returns></returns>
|
||||
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