Play Audio in Queue
Asked Answered
C

2

0

Hey guys,

I have a single Object which has an Audio Source due to only wanting a single audio to play at a time. Besides that i have various interactables which can be clicked in order to play a sound, meaning clicking an object will tell the game manager which sound he should play… this all works fine so far, however when playing two sounds quickly after another only the second sound gets played, which makes sense since only a single Audio Source is present I assume.

What I am looking for is a way to queue Audio files in the game Manager and then play these in a row one after another…

I guess whenever I tap an interactable, I would need to add its Audio Clip to a list, the game manager than plays through the list and deletes the clip from the list once it got played correct ?

But how would you do this ? Using Corountines to determine if the Audio Source is still playing, or rather use PlayScheduled ?

Would be really grateful for some hints and thoughts.

Climactic answered 15/4 at 8:21 Comment(0)
F
0

For me, I would have a SoundManager" script. So I can just use a PlaySound(clip); method whenever I need to. So the SoundManger could look something like this:

public class SoundManager : Monobehaviour
{
    public AudioSource audioSource;
    Queue<AudioClip> clipQueue;
  
    void FixedUpdate()
    {
	    if (audioSource.isPlaying == false && clipQueue.Count > 0) {
	        audioSource.clip = clipQueue.Dequeue();
            audioSource.Play();
	    }
    }
    public void PlaySound(AudioClip clip)
    {
        clipQueue.Enqueue(clip);
    }
}
Faints answered 15/4 at 8:20 Comment(2)

Works like magic, thanks!

Sweetening

if you use a Queue, don't forget to initialize it with clipsQueue = new Queue<AudioClip>(); or it will not work ¯\\(°_o)/¯

Andryc
G
0

Prefer AudioSource.PlayScheduled().

From the docs:

Genista answered 15/4 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.