Home > Enterprise >  How do I get the length of an audio clip from a series in an array?
How do I get the length of an audio clip from a series in an array?

Time:08-12

I'm working on this subtitle system. It has an array of audio clips and an array of texts. I want a single audio clip to play, get the duration of that clip, and wait for that duration. I got my code set up inside the coroutine like this:

 IEnumerator SubtitleCoroutine()
    {
        foreach(string subtitle in _Subtitles)
        {
            foreach(AudioClip audio in audioClips)
            {
                _Text.text=subtitle;
                audioSource.PlayOneShot(audio);
                yield return new WaitForSeconds(audio.length);
            }
        }
    }

But this method plays ALL the audio clips in the array and waits for their total duration to be over. How do I fix this?

CodePudding user response:

You can't use a foreach loop here, because you need to work with both arrays at the same time.

IEnumerator SubtitleCoroutine()
{
    for(int i = 0; i < audioClips.length; i  ){
        _Text.text = _Subtitles[i];
        audioSource.PlayOneShot(audioClips[i]);
        yield return new WaitForSeconds(audioClips[i].length);
    }
}
  • Related