Jozef Benko
Jozef Benko

Reputation: 91

Audio Fade In/Out with C# in Unity?

I just added an audio manager to my android platformer game in Unity and the manager is based on this video tutorial from Brackeys and it is working as expected. I would like to ask someone to help me to understand how can I implement an Audio Fade In/Out code (I think it will be a coroutine) so when the game starts all sounds fade in and when I call a function on a button (an Exit game UI button is already created) than all sounds fade out.

I tried to implement a coroutine from my previous UI Manager script but unfortunately somehow I'm having problems to understand the problem. Every other functionalities of the game are working as I wanted.

Music Class.cs

using UnityEngine.Audio;
using UnityEngine;

[System.Serializable]
public class Classmusic
{
    public string name;

    public AudioClip clip;

    [Range(0f, 1f)]
    public float volume;
    [Range(0.1f, 3f)]
    public float pitch;

    public bool loop;

    [HideInInspector]
    public AudioSource source;
}

Music Player.cs

using System.Collections;
using UnityEngine;
using System;
using UnityEngine.Audio;


public class MPlayer : MonoBehaviour
{
    public Classmusic[] music;

    private void Awake()
    {
        foreach (Classmusic m in music)
        {
            m.source = gameObject.AddComponent<AudioSource>();
            m.source.clip = m.clip;
            m.source.volume = m.volume;
            m.source.pitch = m.pitch;
            m.source.loop = m.loop;
        }
    }

    private void Start()
    {
        Play("MainMusic");
    }

    public void Play (string name)
    {
        Classmusic m = Array.Find(music, sound => sound.name == name);
        if (m == null)
        {
            Debug.LogWarning("Music: " + name + " not found!");
            return;
        }
        m.source.Play();

    }
}

Upvotes: 0

Views: 8227

Answers (3)

Ger Mc
Ger Mc

Reputation: 640

This is my solution for my 2d platformer game. I have a sound fade in/out as my player gets closer/far away from its parent object, I'll call it 'Enemy'.

Audiosource settings on Enemy:

Spatial Blend: 1
Volume Rolloff: = Linear Rolloff
Min distance = 1
Max distance = 30

Place the audio listener on your player object and it should work.

Upvotes: 0

Evgeny Podoynikov
Evgeny Podoynikov

Reputation: 51

In my project I use this solution which allows you to select the fading time and the interpolation function for it (e.g Mathf.Lerp, Mathf.SmoothStep etc.).

Sound.cs

using UnityEngine;

[System.Serializable]
public class Sound
{
    public string name;
    public AudioClip clip;

    [Range(0f, 1f)]
    public float volume;
    [Range(.1f, 3f)]
    public float pitch;

    public bool loop;

    [HideInInspector]
    public AudioSource source;

}

AudioFade.cs

using UnityEngine;
using System.Collections;
using System;

public class AudioFade
{
    public static IEnumerator FadeOut(Sound sound, float fadingTime, Func<float, float, float, float> Interpolate)
    {
        float startVolume = sound.source.volume;
        float frameCount = fadingTime / Time.deltaTime;
        float framesPassed = 0;

        while (framesPassed <= frameCount)
        {
            var t = framesPassed++ / frameCount;
            sound.source.volume = Interpolate(startVolume, 0, t);
            yield return null;
        }

        sound.source.volume = 0;
        sound.source.Pause();
    }
    public static IEnumerator FadeIn(Sound sound, float fadingTime, Func<float, float, float, float> Interpolate)
    {
        sound.source.Play();
        sound.source.volume = 0;

        float resultVolume = sound.volume;
        float frameCount = fadingTime / Time.deltaTime;
        float framesPassed = 0;

        while (framesPassed <= frameCount)
        {
            var t = framesPassed++ / frameCount;
            sound.source.volume = Interpolate(0, resultVolume, t);
            yield return null;
        }

        sound.source.volume = resultVolume;
    }
}

Using:

StartCoroutine(AudioFade.FadeIn(mainThemeSound, 3f, Mathf.SmoothStep));

Upvotes: 5

Flobbinhood
Flobbinhood

Reputation: 710

One issue here is that you have two volumes, one in Classmusic, and one in the AudioSource source variable which is contained in Classmusic. I'm guessing the play function sets source.volume = 0;, but I can't say for sure. Did you try something like this?

IEnumerator FadeIn(Classmusic sound) {
    sound.volume = 0;
    sound.source.volume = 0;
    float speed = 0.01f;   

    for (float i = 0; i < 1; i += speed)
    {
        sound.volume = i;
        sound.source.volume = i;
        yield return null;
    }
}

I know it's irritating to set both variables, but it's probably better to keep them in sync. You could also have a SetVolume() function that sets both the AudioSource volume and the variable inside Classmusic class.

Upvotes: 0

Related Questions