- Home /
Invoke a function when an audio clip is done?
Hi. How can I determine when an audio clip is done playing? Thanks
Answer by syclamoth · Mar 15, 2012 at 03:55 AM
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!
This is so useful!
I have a tutorial for a game going with all these messy invokes and I was looking for a solution like this :-)
Your answer
Follow this Question
Related Questions
Playing ipod audio... 0 Answers
Old Audio Asset File keeps Playing 1 Answer
Sound Cracks or Lags on ZTE Blade? 0 Answers
Switch Audio on Different surfaces 0 Answers
How do you make loop sounds exclusive to distance in C#? 1 Answer