How To Stop An Audio Clip if it's Playing More Than 2 Sounds?

Hey guys, I’ve been trying to figure out how to stop playing the first audio file if two more start playing while the first is still going.

Because right now, if more than two are playing, I get a very bad white noise effect.

Does anyone know how I can achieve this?

you will probly need to have something that will count the number of sound playing and that keep tracks of the sounds playing. Each time an audioSource start (or audioClip or whatever ur using), add it to a list and check if that list got bigger than 2, if yes, stop the first sound and remove it from the list.

Also you can either set a timer the length of the sound to remove itself from the list after it have done playing (if ur not looping ur sound) or go thourgh all the sounds of the list to check if they are still playing when ur adding a new one

    using UnityEngine;
    using System.Collections.Generic;
    
    public class AudioManager : MonoBehaviour {
        // The number of maximum sounds to allow playing simultaneously
        public int maxSoundPlaying = 2;
    
        private List<AudioSource> soundsPlaying = new List<AudioSource>();
    
        public void PlaySound(AudioSource sound) {
            // First remove all the sounds that are done playing
            int i = 0;        
            while (i < soundsPlaying.Count) {
                if (soundsPlaying*.isPlaying) {*

i++;
} else {
soundsPlaying.RemoveAt(i);
}
}

// Then start the sound and add it to the list
sound.Play();
soundsPlaying.Add(sound);

// Check if there is too much sound playing,
// if yes remove the first one of the list
if (soundsPlaying.Count > maxSoundPlaying) {
soundsPlaying[0].Stop();
soundsPlaying.RemoveAt(0)
}
}
}