- Home /
How can I Get An Audio Clip to Play a Certain Number Of Times C#
I'm trying to figure out how to make an audio file loop for a specified amount of times using C# is there a recommended way of doing this?
$$anonymous$$, maybe I need to clarify lol, I don't mean a loop in the classic sense, just a way to code a clip to play say 4 or 5 or as many times as you would like. Something like: audio.loop = true; but with some kind of time statement ins$$anonymous$$d of loop, maybe it needs the loop also? Not sure?
Answer by Chris333 · Feb 02, 2015 at 02:28 PM
Hi,
try something like the following. Your GameObject needs a AudioSource attached.
public AudioClip impact;
void OnMouseDown()
{
StartCoroutine(PlayAudio (3));
}
IEnumerator PlayAudio(int times)
{
for(int i=0; i<times; i++)
{
audio.PlayOneShot(impact, 0.7F);
yield return new WaitForSeconds(impact.length);
}
}
Ahh, yes, this is the sort of thing I was thinking of because I have two seperate instances of how I need to do this, one method is with a button press, and the other is with an animations event. I think with the animation event it might be something like this if I'm understanding it right? public void mySound() { StartCoroutine(PlayAudio (3)); }
IEnumerator PlayAudio(int times)
{
for(int i=0; i<times; i++)
{
audio.PlayOneShot(mySoundt, 0.7F);
yield return new WaitForSeconds(mySound.length);
}
}
Answer by HarshadK · Feb 02, 2015 at 02:26 PM
You can use a counter for that.
Psuedo-code:
int counter = 0; int maxCounterValue = 5;
void Update() or even a Coroutine() {
if(counter < maxCounterValue)
{
if(!audio.IsPlaying())
{
audio.Play();
counter++;
}
}
}
Your answer
Follow this Question
Related Questions
How to Trim off Audio Clip's Tail? 1 Answer
How to check if an AudioClip has looped? 0 Answers
play audio from frequency and amplitude file 0 Answers
Audio loops too early 2 Answers