统一C#-重播声音重叠

时间:2018-12-04 16:50:11

标签: c# unity3d augmented-reality

我这里有一个代码,当找到目标时它会自动播放声音,而在丢失目标时会停止播放声音。我正在做的是要重复当前找到的目标的声音。问题是当我单击“重放”按钮时,找到的最后一个目标的声音和当前目标都在播放。

我在DefaultTrackableEventHandler脚本上对此进行了编码。这是我的代码:

public AudioSource soundTarget;
public AudioClip clipTarget;
private AudioSource[] allAudioSources;
public Button Button;

void StopAllAudio()
    {
        allAudioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
        foreach (AudioSource audioS in allAudioSources)
        {
            audioS.Stop();

        }
    }

void playSound(string ss)
    {
        clipTarget = (AudioClip)Resources.Load(ss);
        soundTarget.clip = clipTarget;
        soundTarget.loop = false;
        soundTarget.playOnAwake = false;
        soundTarget.Play();

    }

public void ReplayAudio()
    {
        soundTarget.PlayOneShot(clipTarget);
    }

在公共虚拟void OnTrackingFound()下

    public virtual void OnTrackingFound()
    {

  if (mTrackableBehaviour.TrackableName == "letterA")
        {
            playSound("sounds/airplane");

            Button.onClick.AddListener(ReplayAudio);
        }

        if (mTrackableBehaviour.TrackableName == "letterB")
        {
            playSound("sounds/banana");

            Button.onClick.AddListener(ReplayAudio);
        }

//正在跟踪时丢失:StopAllAudio();

1 个答案:

答案 0 :(得分:0)

在添加另一个侦听器之前,您需要先在按钮上调用RemoveAllListeners,否则每次找到目标时它们都会堆叠在一起。

public virtual void OnTrackingFound()
{
  Button.onClick.RemoveAllListeners();

  if (mTrackableBehaviour.TrackableName == "letterA")
  {
      playSound("sounds/airplane");
      Button.onClick.AddListener(ReplayAudio);
  }

  if (mTrackableBehaviour.TrackableName == "letterB")
  {
      playSound("sounds/banana");
      Button.onClick.AddListener(ReplayAudio);
  }
}