Hi. How can I determine when an audio clip is done playing? Thanks
Tricky one. There was a discussion this time yesterday about the same thing (you’d have found it if you’d used the search bar), and the general consensus was that nobody really knew how to do it precisely!
Of course, if you don’t really need sample-perfect accuracy, you can always do something like this:
public delegate void AudioCallback();
public void PlaySoundWithCallback(AudioClip clip, AudioCallback callback)
{
audio.PlayOneShot(clip);
StartCoroutine(DelayedCallback(clip.length, callback));
}
private IEnumerator DelayedCallback(float time, AudioCallback callback)
{
yield return new WaitForSeconds(time);
callback();
}
Now, if you have a function that matches the pattern declared in the delegate (you can change this if you feel the need), you can invoke it after an audioclip, using something like this:
void AudioFinished()
{
Debug.Log("Audio Done!");
}
void Start()
{
PlaySoundWithCallback(myClip, AudioFinished);
}
Which will print “Audio Done!” as soon as the clip ends!