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 AudioSourceHapticPulser : RoutineHapticPulser { [Tooltip("The waveform to represent the haptic pattern.")] [SerializeField] private AudioSource audioSource; /// /// The waveform to represent the haptic pattern. /// public AudioSource AudioSource { get { return audioSource; } set { audioSource = value; } } /// /// of the last . /// protected double filterReadDspTime; /// /// Audio data array of the last . /// protected float[] filterReadData; /// /// Number of channels of the last . /// protected int filterReadChannels; /// public override bool IsActive() { return base.IsActive() && AudioSource != 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 outputSampleRate = AudioSettings.outputSampleRate; while (AudioSource.isPlaying) { int sampleIndex = (int)((AudioSettings.dspTime - filterReadDspTime) * outputSampleRate); float currentSample = 0; if (filterReadData != null && sampleIndex * filterReadChannels < filterReadData.Length) { for (int i = 0; i < filterReadChannels; ++i) { currentSample += filterReadData[sampleIndex + i]; } currentSample /= filterReadChannels; } HapticPulser.Intensity = currentSample * IntensityMultiplier; HapticPulser.Begin(); yield return null; } ResetIntensity(); } /// /// Store currently playing audio data and additional data. /// /// An array of floats comprising the audio data. /// An int that stores the number of channels of audio data passed to this delegate. protected virtual void OnAudioFilterRead(float[] data, int channels) { filterReadDspTime = AudioSettings.dspTime; filterReadData = data; filterReadChannels = channels; } } }