如何在Unity C#中的运行时管理AudioSources

时间:2019-05-17 00:49:00

标签: c# unity3d audio-source

在Unity的音乐应用程序中,当您放置淡入淡出以使正在创建的声音停止播放时不会发出喀嗒声时,背景中的所有音乐也会进入淡入淡出。我希望能够在不干扰背景音乐的情况下进行淡入淡出,但我不知道该如何做。这是我的代码:

private AudioSource[] sound;

void OnTouchDown()
{

    if (instrument == "Piano")
    {
        FindObjectOfType<PianoAudioManager>().Play("PianoGmaj1G"); 
    }

void OnTouchUp()
{        
    sound = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
    foreach (AudioSource audioS in sound)
    {
        StartCoroutine(AudioFadeOut.FadeOut(audioS, 0.02f));
    }
}

如何在激活声音时保存声音,以便可以进行淡入淡出而不影响其他所有内容?我已经坚持了好几天,但找不到方法。我将非常感谢您的帮助。谢谢

编辑。是的,抱歉,我的PianoAudioManager代码是:

public class PianoAudioManager : MonoBehaviour{

    public PianoSound[] PianoSounds;

    public static PianoAudioManager instance; 
    public AudioMixerGroup PianoMixer;

    void Awake() 
    {

        if (instance == null)
            instance = this;
        else
        {
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject); 

        foreach(PianoSound s in PianoSounds)
        {
            s.source = gameObject.AddComponent<AudioSource>(); 
            s.source.outputAudioMixerGroup = PianoMixer;
            s.source.clip = s.clip;

            s.source.volume = s.volume;
            s.source.pitch = s.pitch;
        }
    }

    public void Play (string name)
    {
        PianoSound s = Array.Find(PianoSounds, sound => sound.name == name);  
        if (s == null)
        {
            Debug.LogWarning("Sound: " + name + " not found!");
            return;
        }
        s.source.Play();
    }
}

1 个答案:

答案 0 :(得分:0)

现在,您正在淡出场景中的每个AudioSource,但我认为您只想淡出正在播放钢琴噪音的Audiosource。如果正确,那么您需要记住哪个音频源正在播放声音,然后淡出那个声音源!

在PianoAudioManager中添加/更改此内容

public List<PianoSound> soundsToFadeOut = new List<PianoSound>();
public void Play (string name)
{
    PianoSound s = Array.Find(PianoSounds, sound => sound.name == name);  
    if (s == null)
    {
        Debug.LogWarning("Sound: " + name + " not found!");
        return;
    }
    s.source.Play();
soundsToFadeOut.Add(s);
}

并更改其他功能:

void OnTouchDown()
{

    if (instrument == "Piano")
    {
        PianoAudioManager playable = FindObjectOfType<PianoAudioManager>();
        playable.Play("PianoGmaj1G"); 
    }

void OnTouchUp()
{        
    PianoAudioManager playable = FindObjectOfType<PianoAudioManager>();
    foreach (PianoSound s in playable.soundsToFadeout)
    {
        StartCoroutine(AudioFadeOut.FadeOut(s.source, 0.02f));
    }
    playable.soundsToFadeout.Clear();
}

说明:
您想跟踪实际播放的声音,只淡出那些歌曲!