- Home /
The question is answered, right answer was accepted
How to make a loop yield for the length of audio,how to make a loop wait for audio lengh
I have multiple audio sources through out the scene. I created a coroutine so the audio loops through all the audio sources.
public List<AudioSource> sourcesInScene; //assign these in the inspector
private List<int> indexCountA = new List<int>();
public void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
ResetIndexCountA(sourcesInScene.Count);
StartCoroutine(RandomPlayBack());
}
private void ResetIndexCountA(int number)
{
indexCountA.Clear();
for (int i = 0; i < number; i++)
{
indexCountA.Add(i);
}
}
IEnumerator RandomPlayBack()
{
//we're using an ienumerator so we can "wait" between loops.
while (indexCountA.Count != 0)
{
for (int x = 0; x < sourcesInScene.Count; x++)
{
var i = Random.Range(0, indexCountA.Count);
sourcesInScene[indexCountA[i]].Play();
indexCountA.RemoveAt(i);
yield return new WaitForSeconds(1f);
}
yield return null;
}
}
My question is on the line where I wrote "yield retrun new WaitForSeconds(1f);" instead of me specifing the yield time such as 1f how can I make it so it loops as soon as the previous audio is finished playing. Remember am not just playing audio clips, where i could yield using audioclip.length. I am working with multiple audio sources.
,
Can you mix all of the audio into one audio track and then loop that one audio clip?
An AudioSource has a time attribute. So whenever you start an additional source just subtract each time from each clip length, sort them by the longest time and yield that.
Answer by Eno-Khaon · Jun 22, 2017 at 03:34 AM
Maybe I'm misunderstanding something, but can you not still use AudioClip.length? Specifically...
sourcesInScene[indexCountA[i]].clip.length
... should hook to the AudioClip assigned to the AudioSource that you're instructing to play. In that case, you can simply swap two lines and you should be good to go.
sourcesInScene[indexCountA[i]].Play();
yield return new WaitForSeconds(sourcesInScene[indexCountA[i]].clip.length);
indexCountA.RemoveAt(i);
thank you man i did not know i could use length attribute for audiosources
I've converted this to an answer - please accept this answer if it solves your problem (it was posted before $$anonymous$$e).
Answer by aldonaletto · Jun 22, 2017 at 08:05 PM
Why can't you use the clip length? Save it in a variable and set the delay in the yield:
for (int x = 0; x < sourcesInScene.Count; x++) {
var i = Random.Range(0, indexCountA.Count);
AudioSource aud = sourcesInScene[indexCountA[i]]; // get a reference to the AudioSource [i]
float duration = aud.clip.length; // get its duration in a variable
aud.Play(); // start playing
indexCountA.RemoveAt(i); // remove it from the list
yield return new WaitForSeconds(duration); // wait the clip finish playing
}