I am trying to add a simple footstep sound (16 bit, 44100 Hz, 00:00.498 86.9KB WAV) to an fps player using the code below. Most of this code I got from searching other posts on the subject:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (AudioSource))]
public class PlayerSound : MonoBehaviour
{
public AudioClip[] playerSounds = new AudioClip[9];
void Update()
{
PlaySound ();
}
void PlaySound()
{
if(Input.GetAxis("Vertical") != 0f)
{
audio.clip = playerSounds[0];
if(!audio.isPlaying)
{
audio.Play();
}
else if(audio.isPlaying)
{
audio.Pause ();
}
}
}
}
When I move the player forward the sound plays more rapidly than it should (far more rapidly if I use audio.Stop() in the else if statement) and seems to add a very faint echo of the accelerated sound immediately after having been played. This effectively distorts the sound just enough to present some semblance of the original audio, but not enough to accurately be called similar. I figure it must have something to do with the calling the audio clip to quickly, but I can’t seem to figure out how to slow that call down. The closest I came was by doing this:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (AudioSource))]
public class PlayerSound : MonoBehaviour
{
public AudioClip[] playerSounds = new AudioClip[9];
void Update()
{
StartCoroutine(PlayWalk());
}
IEnumerator PlayWalk()
{
if(Input.GetAxis("Vertical") != 0f)
{
audio.clip = playerSounds[0];
if(!audio.isPlaying)
{
audio.Play();
}
else if(audio.isPlaying)
{
yield return new WaitForSeconds(1);
audio.Stop ();
}
}
}
}
But this was a very temporary fix. Depending on the value of the argument in the WaitForSeconds method, the sound would play as desired (without distortion and playing the entire clip) only for about the length of the value. The clip would then go silent and would not resume again for a number of seconds. Does anyone have any insight into what I might be doing wrong? Forgive me if it is something silly, but I haven’t been coding for very long. Thanks.