I recently noticed that the short WAV sounds I have attached to my game collectibles, are sometimes missed.
So I started investigating, and stripped all the unnecessary code, to see where the problem is. The result is the below test script.
It appears that short WAV files are sometimes not played.
I have used the following script to test it (of course, an audio listener is attached to the camera):
Ok, here is my solution: Create an AudioSource manually and hook up the AudioClip via the inspector or through code. Then play the source like this:
using UnityEngine;
using System.Collections;
public class SoundTester : MonoBehaviour
{
public AudioClip sound;
public AudioSource source;
float timeSinceLast = 0;
void Start()
{
source.clip = sound;
}
void Update ()
{
if( Time.time - timeSinceLast > 0.6f )
{
Debug.Log("Playing");
timeSinceLast = Time.time;
// AudioSource.PlayClipAtPoint( sound, Camera.main.transform.position );
source.Play();
}
}
}
The “bug” is not really a bug. The static method PlayClipAtPoint creates an AudioSource automatically when it needs to play and disposes of it, once the clip is done. When playing a longer sound once, this is not a problem, but when you do it at a short interval, this will create and destroy this hidden AudioSource every time, causing hiccups in framerate. You can actually see the gameobject being created and destroyed in the hierarchy sometimes. Although most of the time the refresh is too slow to actually show it. However, this instantiating is very expensive and you really shouldn’t be doing it this often. The actually drop out happens as soon as enough memory garbage has collected from destroying the implicit AudioSource and the Garbage Collector runs to get rid of those unused references.
Solution: Manually creating an AudioSource, assigning a clip and then playing it will not create any garbage and therefore runs smoothly.
However, it still may be a bug that the implicitly created AudioSource is creating so much garbage. One might expect it to be optimized better. So if you are going to submit it as a bug, better call it an optimization request, but probably not much chance of getting a fix on this. Just use the manual way.