Search Unity

Audio How to manage AudioSources at runtime

Discussion in 'Audio & Video' started by JossVicore, May 18, 2019.

  1. JossVicore

    JossVicore

    Joined:
    Feb 28, 2019
    Posts:
    3
    Hello.
    I'm trying to do a music application in Unity.

    I have a problem when I apply a fadeout to mute the sounds that are being created to don't have clicking when they stop.
    All the music that is in the background also enters into the fadeout. I would like to be able to do fadeout without interfering in the background music, but i don't know how. This is my code:


    Code (CSharp):
    1. private AudioSource[] sound;
    2.  
    3. void OnTouchDown()
    4. {
    5.  
    6.     if (instrument == "Piano")
    7.     {
    8.         FindObjectOfType<PianoAudioManager>().Play("PianoGmaj1G");
    9.     }
    10.  
    11. void OnTouchUp()
    12. {      
    13.     sound = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
    14.     foreach (AudioSource audioS in sound)
    15.     {
    16.         StartCoroutine(AudioFadeOut.FadeOut(audioS, 0.02f));
    17.     }
    How could I save the sound when I activate it so I can do the fadeout without affecting everything else? I have been stuck with this for days and I can not find how to do it. I would be very grateful for any help. Thank you

    My PianoAudioManager code is:

    Code (CSharp):
    1. public class PianoAudioManager : MonoBehaviour{
    2.  
    3. public PianoSound[] PianoSounds;
    4.  
    5. public static PianoAudioManager instance;
    6. public AudioMixerGroup PianoMixer;
    7.  
    8. void Awake()
    9. {
    10.  
    11.     if (instance == null)
    12.         instance = this;
    13.     else
    14.     {
    15.         Destroy(gameObject);
    16.         return;
    17.     }
    18.  
    19.     DontDestroyOnLoad(gameObject);
    20.  
    21.     foreach(PianoSound s in PianoSounds)
    22.     {
    23.         s.source = gameObject.AddComponent<AudioSource>();
    24.         s.source.outputAudioMixerGroup = PianoMixer;
    25.         s.source.clip = s.clip;
    26.  
    27.         s.source.volume = s.volume;
    28.         s.source.pitch = s.pitch;
    29.     }
    30. }
    31.  
    32. public void Play (string name)
    33. {
    34.     PianoSound s = Array.Find(PianoSounds, sound => sound.name == name);
    35.     if (s == null)
    36.     {
    37.         Debug.LogWarning("Sound: " + name + " not found!");
    38.         return;
    39.     }
    40.     s.source.Play();
    41. }
    42.  
    43. }