Home > front end >  How to Fade Audio In Unity C#
How to Fade Audio In Unity C#

Time:09-17

I wrote a script that plays random audio files from an array. But I can't figure out how to fade out the current playing audio at the end of the file and fade in the new audio file. below is the code. The Audio file I am using is mp3 files for now and I have a plan to switch to wave files. and any suggestion to that too

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Random = UnityEngine.Random;
public class BackGroundAudio : MonoBehaviour
{
    public AudioSource audioSource;
    public AudioClip[] audioClipsArray;
    public String FileName;
    // Start is called before the first frame update

    void awake()
    {
       audioSource = GetComponent<AudioSource>(); 
       
    }
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (!audioSource.isPlaying)
         {
             PlayRandom();
         }
    }

    void PlayRandom()
    {
        audioSource.clip=audioClipsArray[Random.Range(0,audioClipsArray.Length)];
        audioSource.clip =trimSilence(audioSource.clip);
        audioSource.PlayOneShot(audioSource.clip);
    }
    AudioClip trimSilence(AudioClip inputAudio, float threshold = 0.05f)
    {
        // Copy samples from input audio to an array. AudioClip uses interleaved format so the length in samples is multiplied by channel count
        float[] samplesOriginal = new float[inputAudio.samples * inputAudio.channels];
        inputAudio.GetData(samplesOriginal, 0);
        // Find first and last sample (from any channel) that exceed the threshold
        int audioStart = Array.FindIndex(samplesOriginal, sample => sample > threshold),
            audioEnd = Array.FindLastIndex(samplesOriginal, sample => sample > threshold);
        // Copy trimmed audio data into another array
        float[] samplesTrimmed = new float[audioEnd - audioStart];
        Array.Copy(samplesOriginal, audioStart, samplesTrimmed, 0, samplesTrimmed.Length);
        // Create new AudioClip for trimmed audio data
        AudioClip trimmedAudio = AudioClip.Create(inputAudio.name, samplesTrimmed.Length / inputAudio.channels, inputAudio.channels, inputAudio.frequency, false);
        trimmedAudio.SetData(samplesTrimmed, 0);
        return trimmedAudio;
    }
}

CodePudding user response:

Something like this should do it, you can do better solutions with audio mixers but I believe this is the lowest effort/easiest implementation.

In words: when you start a clip, it will set the audioSource's volume from 0 to 1 over FADE_TIME_SECONDS seconds. And then at the same time, we start a Coroutine delayed with the clip's length minus FADE_TIME_SECONDS and do the same, but from 1 to 0, which sets up for the next track, starting volume at 0 and fading in.

In code:

const float FADE_TIME_SECONDS = 5;

void PlayRandom()
{
    StartCoroutine(FadeIn());

    audioSource.clip = audioClipsArray[Random.Range(0,audioClipsArray.Length)];
    audioSource.clip = trimSilence(audioSource.clip);
    audioSource.PlayOneShot(audioSource.clip);
    
    StartCoroutine(FadeOut(audioSource.clip.length - FADE_TIME_SECONDS));
}

IEnumerator FadeOut(float delay) 
{
    yield return new WaitForSeconds(delay);
    var timeElapsed = 0;

    while (audioSource.volume > 0) 
    {
        audioSource.volume = Mathf.Lerp(1, 0, timeElapsed / FADE_TIME_SECONDS);
        timeElapsed  = Time.deltaTime;
        yield return;
    }
}

IEnumerator FadeIn() 
{
    var timeElapsed = 0;

    while (audioSource.volume < 1) 
    {
        audioSource.volume = Mathf.Lerp(0, 1, timeElapsed / FADE_TIME_SECONDS);
        timeElapsed  = Time.deltaTime;
        yield return;
    }
}
  • Related