namespace Zinnia.Haptics
{
using System.Collections;
using UnityEngine;
///
/// Creates a haptic pattern based on the waveform of an and utilizes a to create the effect.
///
public class AudioClipHapticPulser : RoutineHapticPulser
{
[Tooltip("The waveform to represent the haptic pattern.")]
[SerializeField]
private AudioClip audioClip;
///
/// The waveform to represent the haptic pattern.
///
public AudioClip AudioClip
{
get
{
return audioClip;
}
set
{
audioClip = value;
}
}
///
/// The size of the audio buffer.
///
protected const int BufferSize = 8192;
///
/// The audio data buffer.
///
protected readonly float[] audioData = new float[BufferSize];
///
public override bool IsActive()
{
return base.IsActive() && AudioClip != null;
}
///
/// Enumerates through and pulses for each amplitude of the wave.
///
/// An Enumerator to manage the running of the Coroutine.
protected override IEnumerator HapticProcessRoutine()
{
int sampleOffset = -BufferSize;
float startTime = Time.time;
float length = AudioClip.length;
float endTime = startTime + length;
float sampleRate = AudioClip.samples;
while (Time.time <= endTime)
{
float lerpVal = (Time.time - startTime) / length;
int sampleIndex = (int)(sampleRate * lerpVal);
if (sampleIndex >= sampleOffset + BufferSize)
{
AudioClip.GetData(audioData, sampleIndex);
sampleOffset = sampleIndex;
}
float currentSample = Mathf.Abs(audioData[sampleIndex - sampleOffset]);
HapticPulser.Intensity = currentSample * IntensityMultiplier;
HapticPulser.Begin();
yield return null;
}
ResetIntensity();
}
}
}